<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Stefan Angrick</title>
    <link>https://stefan.angrick.me/</link>
    <description></description>
    <pubDate>Mon, 20 Apr 2026 01:32:23 +0000</pubDate>
    <item>
      <title>Google ML Crash Course #4 Notes: Real-World ML</title>
      <link>https://stefan.angrick.me/google-ml-crash-course-4-notes-real-world-ml?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[This post is part of a four-part summary of Google&#39;s Machine Learning Crash Course. For context, check out this post. This fourth module covers critical considerations when building and deploying ML models in the real world, including productionisation best practices, automation, and responsible engineering.!--more--&#xA;&#xA;Production ML systems&#xA;&#xA;Introduction&#xA;&#xA;The model is only a small part of real-world production ML systems. It often represents only 5% or less of the total codebase in the system.&#xA;MlSystem.png&#xA;&#xA;Source: Production ML systems | Machine Learning | Google for Developers&#xA;&#xA;Static versus dynamic training&#xA;&#xA;Machine learning models can be trained statically (once) or dynamically (continuously).&#xA;&#xA;|                   | Static training (offline training)                                                            | Dynamic training (online training)                                                               |&#xA;| ----------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |&#xA;| Advantages    | Simpler. You only need to develop and test the model once.                                | More adaptable. Keeps up with changes in data patterns, providing more accurate predictions. |&#xA;| Disadvantages | Sometimes stale. Can become outdated if data patterns change, requiring data monitoring. | More work. You must build, test, and release a new product continuously.                     |&#xA;&#xA;Choosing between static and dynamic training depends on the specific dataset and how frequently it changes.&#xA;&#xA;Monitoring input data is essential for both static and dynamic training to ensure reliable predictions.&#xA;&#xA;Source: Production ML systems: Static versus dynamic training | Machine Learning | Google for Developers&#xA;&#xA;Static versus dynamic inference&#xA;&#xA;Inference involves using a trained model to make predictions on unlabelled examples, and it can be done as follows:&#xA;&#xA;Static inference (offline inference, batch inference) generates predictions in advance and caches them, which suits scenarios where prediction speed is critical.&#xA;&#xA;Dynamic inference (online inference, real-time inference) generates predictions on demand, offering flexibility for diverse inputs.&#xA;&#xA;|                   | Static inference (offline inference, batch inference)                                               | Dynamic inference (online inference, real-time inference)               |&#xA;| ----------------- | --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |&#xA;| Advantages    | No need to worry about cost of inference; allows post-verification of predictions before pushing | Can infer a prediction on any new item as it comes in                   |&#xA;| Disadvantages | Limited ability to handle uncommon inputs                                                    | Compute-intensive and latency-sensitive; monitoring needs are intensive |&#xA;&#xA;Choosing between static and dynamic inference depends on factors such as model complexity, desired prediction speed, and the nature of the input data.&#xA;&#xA;Static inference is advantageous when cost and prediction verification are prioritised, while dynamic inference excels in handling diverse, real-time predictions.&#xA;&#xA;Source: Production ML systems: Static versus dynamic inference | Machine Learning | Google for Developers&#xA;&#xA;When to transform data?&#xA;&#xA;Feature engineering can be performed before or during model training, each with its own advantages and disadvantages.&#xA;&#xA;Transforming data before training allows for a one-time transformation of the entire dataset but requires careful recreation of transformations during prediction to avoid training-serving skew.&#xA;Transforming data during training ensures consistency between training and prediction but can increase model latency and complicate batch processing.&#xA;  When transforming data during training, considerations such as Z-score normalisation across batches with varying distributions need to be addressed.&#xA;&#xA;Source: Production ML systems: When to transform data? | Machine Learning | Google for Developers&#xA;&#xA;Deployment testing&#xA;&#xA;Deploying a machine learning model involves validating data, features, model versions, serving infrastructure, and pipeline integration.&#xA;&#xA;Reproducible model training involves deterministic seeding, fixed initialisation order, averaging multiple runs, and using version control.&#xA;&#xA;Integration tests ensure that different components of the ML pipeline work together seamlessly and should run continuously and for new model or software versions.&#xA;&#xA;Before serving a new model, validate its quality by checking for sudden and gradual degradations against previous versions and fixed thresholds.&#xA;&#xA;Ensure model-infrastructure compatibility by staging the model in a sandboxed server environment to avoid dependency conflicts.&#xA;&#xA;Source: Production ML systems: Deployment testing | Machine Learning | Google for Developers&#xA;&#xA;Monitoring pipelines&#xA;&#xA;ML pipeline monitoring involves validating data (using data schemas) and features (using unit tests), tracking real-world metrics, and addressing potential biases in data slices.&#xA;&#xA;Monitoring training-serving skew, label leakage, model age, and numerical stability is crucial for maintaining pipeline health and model performance.&#xA;&#xA;Training-serving skew means that input data during training differs from input data during serving, for example because training and serving data use different schemas (schema skew) or because engineered data differs between training and serving (feature skew).&#xA;Label leakage means that the ground truth labels being predicted have inadvertently entered the training features.&#xA;Numerical stability involves writing tests to check for NaN and Inf values in weights and layer outputs, and testing that more than half of the outputs of a layer are not zero.&#xA;&#xA;Live model quality testing uses methods such as human labelling and statistical analysis to ensure ongoing model effectiveness in real-world scenarios.&#xA;&#xA;Implementing proper randomisation through deterministic data generation enables reproducible experiments and consistent analysis.&#xA;&#xA;Maintaining invariant hashing ensures that data splits remain consistent across experiments, contributing to reliable analysis and model evaluation.&#xA;&#xA;Source: Production ML systems: Monitoring pipelines | Machine Learning | Google for Developers&#xA;&#xA;Questions to ask&#xA;&#xA;Continuously monitor models in production to evaluate feature importance and potentially remove unnecessary features, ensuring prediction quality and resource efficiency.&#xA;&#xA;Regularly assess whether features are genuinely helpful and whether their value outweighs the cost of inclusion.&#xA;&#xA;Data reliability is crucial. Consider data source stability, potential changes in upstream data processes, and the creation of local data copies to control versioning and mitigate risks.&#xA;&#xA;Be aware of feedback loops, where a model&#39;s predictions influence future input data, potentially leading to unexpected behaviour or biased outcomes, especially in interconnected systems.&#xA;&#xA;Source: Production ML systems: Questions to ask | Machine Learning | Google for Developers&#xA;&#xA;Automated machine learning&#xA;&#xA;Introduction&#xA;&#xA;AutoML automates tasks in the machine learning workflow, such as data engineering (feature selection and engineering), training (algorithm selection and hyperparameter tuning), and analysis, making model building faster and easier.&#xA;ml-workflow.png&#xA;&#xA;While manual training involves writing code and iteratively adjusting it, AutoML reduces repetitive work and the need for specialised skills.&#xA;&#xA;Source: Automated Machine Learning (AutoML) | Google for Developers&#xA;&#xA;Benefits and limitations&#xA;&#xA;Benefits:&#xA;&#xA;To save time.&#xA;To improve the quality of an ML model.&#xA;To build an ML model without needing specialised skills.&#xA;To smoke test a dataset. AutoML can give quick baseline estimates of whether a dataset has enough signal relative to noise.&#xA;To evaluate a dataset. AutoML can help determine which features may be worth using.&#xA;To enforce best practices. Automation includes built-in support for applying ML best practices.&#xA;&#xA;Limitations:&#xA;&#xA;Model quality may not match that of manual training.&#xA;Model search and complexity can be opaque. Models generated with AutoML are difficult to reproduce manually.&#xA;Multiple AutoML runs may show greater variance.&#xA;Models cannot be customised during training.&#xA;&#xA;Large amounts of data are generally required for AutoML, although specialised systems using transfer learning (taking a model trained on one task and adapting its learned representations to a different but related task) can reduce this requirement.&#xA;&#xA;AutoML suits teams with limited ML experience or those seeking productivity gains without customisation needs. Custom (manual) training suits cases where model quality and customisation matter most.&#xA;&#xA;Source: AutoML: Benefits and limitations | Machine Learning | Google for Developers&#xA;&#xA;Getting started&#xA;&#xA;AutoML tools fall into two categories:&#xA;&#xA;Tools that require no coding.&#xA;API and CLI tools.&#xA;&#xA;The AutoML workflow follows steps similar to traditional machine learning, including problem definition, data gathering, preparation, model development, evaluation, and potential retraining.&#xA;&#xA;Some AutoML systems also support model deployment.&#xA;&#xA;Data preparation is crucial for AutoML and involves labelling, cleaning and formatting data, and applying feature transformations.&#xA;&#xA;No-code AutoML tools guide users through model development with steps such as data import, analysis, refinement, and configuration of run parameters before starting the automated training process.&#xA;&#xA;Users still need to carry out semantic checks to select the appropriate semantic type for each feature (for example recognising that postal codes are categorical rather than numeric), and to set transformations accordingly.&#xA;&#xA;Source: AutoML: Getting started | Machine Learning | Google for Developers&#xA;&#xA;Fairness&#xA;&#xA;Introduction&#xA;&#xA;Before putting a model into production, it is critical to audit training data and evaluate predictions for bias.&#xA;&#xA;Source: Fairness | Machine Learning | Google for Developers&#xA;&#xA;Types of bias&#xA;&#xA;Machine learning models can be susceptible to bias due to human involvement in data selection and curation.&#xA;&#xA;Understanding common human biases is crucial for mitigating their impact on model predictions.&#xA;&#xA;Types of bias include reporting bias, historical bias, automation bias, selection bias, coverage bias, non-response bias, sampling bias, group attribution bias (in-group bias and out-group homogeneity bias), implicit bias, confirmation bias, and experimenter&#39;s bias, among others.&#xA;&#xA;Source: Fairness: Types of bias | Machine Learning | Google for Developers&#xA;&#xA;Identifying bias&#xA;&#xA;Missing or unexpected feature values in a dataset can indicate potential sources of bias.&#xA;&#xA;Data skew, where certain groups are under- or over-represented, can introduce bias and should be addressed.&#xA;&#xA;Evaluating model performance by subgroup ensures fairness and equal performance across different characteristics.&#xA;&#xA;Source: Fairness: Identifying bias | Machine Learning | Google for Developers&#xA;&#xA;Mitigating bias&#xA;&#xA;Machine learning engineers use two primary strategies to mitigate bias in models:&#xA;&#xA;Augmenting training data.&#xA;Adjusting the model&#39;s loss function.&#xA;&#xA;Augmenting training data involves collecting additional data to address missing, incorrect, or skewed data, but it can be infeasible due to data availability or resource constraints.&#xA;&#xA;Adjusting the model&#39;s loss function involves using fairness-aware optimisation functions rather than the common default log loss.&#xA;&#xA;The TensorFlow Model Remediation Library provides optimisation functions designed to penalise errors in a fairness-aware manner:&#xA;&#xA;MinDiff aims to balance errors between different data slices by penalising differences in prediction distributions.&#xA;Counterfactual Logit Pairing (CLP) penalises discrepancies in predictions for similar examples with different sensitive attribute values.&#xA;&#xA;Source: Fairness: Mitigating bias | Machine Learning | Google for Developers&#xA;&#xA;Evaluating for bias&#xA;&#xA;Aggregate model performance metrics such as precision, recall, and accuracy can hide biases against minority groups.&#xA;&#xA;Fairness in model evaluation involves ensuring equitable outcomes across different demographic groups.&#xA;&#xA;Fairness metrics can help assess model predictions for bias.&#xA;&#xA;Demographic parity&#xA;Equality of opportunity&#xA;Counterfactual fairness&#xA;&#xA;Candidate pool of 100 students: 80 students belong to the majority group (blue), and 20 students belong to the minority group (orange):&#xA;fairnessmetricscandidatepool.png&#xA;&#xA;Source: Fairness: Evaluating for bias | Machine Learning | Google for Developers&#xA;&#xA;Demographic parity&#xA;&#xA;Demographic parity aims to ensure equal acceptance rates for majority and minority groups, regardless of individual qualifications.&#xA;&#xA;Both the majority (blue) and minority (orange) groups have an acceptance rate of 20%:&#xA;fairnessmetricsdemographicparity.png&#xA;&#xA;While demographic parity promotes equal representation, it can overlook differences in individual qualifications within each group, potentially leading to unfair outcomes.&#xA;&#xA;Qualified students in both groups are shaded in green, and qualified students who were rejected are marked with an X:&#xA;fairnessmetricsdemographicparitybyqualifications.png&#xA;&#xA;Majority acceptance rate = Qualified majority accepted / Qualified majority = 16/35 = 46%&#xA;Minority acceptance rate = Qualified minority accepted / Qualified minority = 4/15 = 27%&#xA;&#xA;When the distribution of a preferred label (&#34;qualified&#34;) differs substantially between groups, demographic parity may not be the most appropriate fairness metric.&#xA;&#xA;There may be additional benefits/drawbacks of demographic parity not discussed here that are also worth considering.&#xA;&#xA;Source: Fairness: Demographic parity | Machine Learning | Google for Developers&#xA;&#xA;Equality of opportunity&#xA;&#xA;Equality of opportunity focuses on ensuring that qualified individuals have an equal chance of acceptance, regardless of demographic group.&#xA;&#xA;Qualified students in both groups are shaded in green:&#xA;fairnessmetricsequalityofopportunitybyqualifications.png&#xA;&#xA;Majority acceptance rate = Qualified majority accepted / Qualified majority = 14/35 = 40%&#xA;Minority acceptance rate = Qualified minority accepted / Qualified minority = 6/15 = 40%&#xA;&#xA;Equality of opportunity has limitations, including reliance on a clearly defined preferred label and challenges in settings that lack demographic data.&#xA;&#xA;It is possible for a model to satisfy both demographic parity and equality of opportunity under specific conditions where positive prediction rates and true positive rates align across groups.&#xA;&#xA;Source: Fairness: Equality of opportunity | Machine Learning | Google for Developers&#xA;&#xA;Counterfactual fairness&#xA;&#xA;Counterfactual fairness evaluates fairness by comparing predictions for similar individuals who differ only in a sensitive attribute such as demographic group.&#xA;&#xA;This metric is particularly useful when datasets lack complete demographic information for most examples but contain it for a subset.&#xA;&#xA;Candidate pool, with demographic group membership unknown for most candidates (icons shaded in grey):&#xA;fairnessmetricscounterfactualsatisfied.png&#xA;&#xA;Counterfactual fairness may not capture broader systemic biases across subgroups. Other fairness metrics, such as demographic parity and equality of opportunity, provide a more holistic view but may require complete demographic data.&#xA;&#xA;Summary&#xA;&#xA;Selecting the appropriate fairness metric depends on the specific application and desired outcome, with no single &#34;right&#34; metric universally applicable.&#xA;&#xA;For example, if the goal is to achieve equal representation, demographic parity may be the optimal metric. If the goal is to achieve equal opportunity, equality of opportunity may be the best metric.&#xA;&#xA;Some definitions of fairness are mutually incompatible.&#xA;&#xA;Source: Fairness: Counterfactual fairness | Machine Learning | Google for Developers]]&gt;</description>
      <content:encoded><![CDATA[<p>This post is part of a four-part summary of Google&#39;s <a href="https://developers.google.com/machine-learning/crash-course/">Machine Learning Crash Course</a>. For context, check out <a href="notes-from-googles-machine-learning-crash-course">this post</a>. This fourth module covers critical considerations when building and deploying ML models in the real world, including productionisation best practices, automation, and responsible engineering.</p>

<h2 id="production-ml-systems" id="production-ml-systems">Production ML systems</h2>

<h3 id="introduction" id="introduction">Introduction</h3>

<p>The model is only a small part of real-world production ML systems. It often represents only 5% or less of the total codebase in the system.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/MlSystem.png" alt="MlSystem.png"/></p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/production-ml-systems">Production ML systems | Machine Learning | Google for Developers</a></p>

<h3 id="static-versus-dynamic-training" id="static-versus-dynamic-training">Static versus dynamic training</h3>

<p>Machine learning models can be trained statically (once) or dynamically (continuously).</p>

<table>
<thead>
<tr>
<th></th>
<th>Static training (offline training)</th>
<th>Dynamic training (online training)</th>
</tr>
</thead>

<tbody>
<tr>
<td><strong>Advantages</strong></td>
<td><strong>Simpler.</strong> You only need to develop and test the model once.</td>
<td><strong>More adaptable.</strong> Keeps up with changes in data patterns, providing more accurate predictions.</td>
</tr>

<tr>
<td><strong>Disadvantages</strong></td>
<td><strong>Sometimes stale.</strong> Can become outdated if data patterns change, requiring data monitoring.</td>
<td><strong>More work.</strong> You must build, test, and release a new product continuously.</td>
</tr>
</tbody>
</table>

<p>Choosing between static and dynamic training depends on the specific dataset and how frequently it changes.</p>

<p>Monitoring input data is essential for both static and dynamic training to ensure reliable predictions.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/production-ml-systems/static-vs-dynamic-training">Production ML systems: Static versus dynamic training | Machine Learning | Google for Developers</a></p>

<h3 id="static-versus-dynamic-inference" id="static-versus-dynamic-inference">Static versus dynamic inference</h3>

<p>Inference involves using a trained model to make predictions on unlabelled examples, and it can be done as follows:</p>
<ul><li><p><strong>Static inference</strong> (<strong>offline inference</strong>, <strong>batch inference</strong>) generates predictions in advance and caches them, which suits scenarios where prediction speed is critical.</p></li>

<li><p><strong>Dynamic inference</strong> (<strong>online inference</strong>, <strong>real-time inference</strong>) generates predictions on demand, offering flexibility for diverse inputs.</p></li></ul>

<table>
<thead>
<tr>
<th></th>
<th>Static inference (offline inference, batch inference)</th>
<th>Dynamic inference (online inference, real-time inference)</th>
</tr>
</thead>

<tbody>
<tr>
<td><strong>Advantages</strong></td>
<td>No need to worry about cost of inference; allows post-verification of predictions before pushing</td>
<td>Can infer a prediction on any new item as it comes in</td>
</tr>

<tr>
<td><strong>Disadvantages</strong></td>
<td>Limited ability to handle uncommon inputs</td>
<td>Compute-intensive and latency-sensitive; monitoring needs are intensive</td>
</tr>
</tbody>
</table>

<p>Choosing between static and dynamic inference depends on factors such as model complexity, desired prediction speed, and the nature of the input data.</p>

<p>Static inference is advantageous when cost and prediction verification are prioritised, while dynamic inference excels in handling diverse, real-time predictions.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/production-ml-systems/static-vs-dynamic-inference">Production ML systems: Static versus dynamic inference | Machine Learning | Google for Developers</a></p>

<h3 id="when-to-transform-data" id="when-to-transform-data">When to transform data?</h3>

<p>Feature engineering can be performed before or during model training, each with its own advantages and disadvantages.</p>
<ul><li>Transforming data <strong>before training</strong> allows for a one-time transformation of the entire dataset but requires careful recreation of transformations during prediction to avoid training-serving skew.</li>
<li>Transforming data <strong>during training</strong> ensures consistency between training and prediction but can increase model latency and complicate batch processing.
<ul><li>When transforming data during training, considerations such as Z-score normalisation across batches with varying distributions need to be addressed.</li></ul></li></ul>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/production-ml-systems/transforming-data">Production ML systems: When to transform data? | Machine Learning | Google for Developers</a></p>

<h3 id="deployment-testing" id="deployment-testing">Deployment testing</h3>

<p><strong>Deploying</strong> a machine learning model involves validating data, features, model versions, serving infrastructure, and pipeline integration.</p>

<p><strong>Reproducible model training</strong> involves deterministic seeding, fixed initialisation order, averaging multiple runs, and using version control.</p>

<p><strong>Integration tests</strong> ensure that different components of the ML pipeline work together seamlessly and should run continuously and for new model or software versions.</p>

<p>Before serving a new model, <strong>validate</strong> its quality by checking for sudden and gradual degradations against previous versions and fixed thresholds.</p>

<p>Ensure <strong>model-infrastructure compatibility</strong> by staging the model in a sandboxed server environment to avoid dependency conflicts.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/production-ml-systems/deployment-testing">Production ML systems: Deployment testing | Machine Learning | Google for Developers</a></p>

<h3 id="monitoring-pipelines" id="monitoring-pipelines">Monitoring pipelines</h3>

<p><strong>ML pipeline monitoring</strong> involves validating data (using data schemas) and features (using unit tests), tracking real-world metrics, and addressing potential biases in data slices.</p>

<p>Monitoring training-serving skew, label leakage, model age, and numerical stability is crucial for maintaining pipeline health and model performance.</p>
<ul><li><strong>Training-serving skew</strong> means that input data during training differs from input data during serving, for example because training and serving data use different schemas (schema skew) or because engineered data differs between training and serving (feature skew).</li>
<li><strong>Label leakage</strong> means that the ground truth labels being predicted have inadvertently entered the training features.</li>
<li><strong>Numerical stability</strong> involves writing tests to check for NaN and Inf values in weights and layer outputs, and testing that more than half of the outputs of a layer are not zero.</li></ul>

<p><strong>Live model quality testing</strong> uses methods such as human labelling and statistical analysis to ensure ongoing model effectiveness in real-world scenarios.</p>

<p>Implementing <strong>proper randomisation</strong> through deterministic data generation enables reproducible experiments and consistent analysis.</p>

<p>Maintaining invariant <strong>hashing</strong> ensures that data splits remain consistent across experiments, contributing to reliable analysis and model evaluation.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/production-ml-systems/monitoring">Production ML systems: Monitoring pipelines | Machine Learning | Google for Developers</a></p>

<h3 id="questions-to-ask" id="questions-to-ask">Questions to ask</h3>

<p>Continuously monitor models in production to <strong>evaluate feature importance</strong> and potentially remove unnecessary features, ensuring prediction quality and resource efficiency.</p>
<ul><li>Regularly assess whether features are genuinely helpful and whether their value outweighs the cost of inclusion.</li></ul>

<p><strong>Data reliability</strong> is crucial. Consider data source stability, potential changes in upstream data processes, and the creation of local data copies to control versioning and mitigate risks.</p>

<p>Be aware of <strong>feedback loops</strong>, where a model&#39;s predictions influence future input data, potentially leading to unexpected behaviour or biased outcomes, especially in interconnected systems.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/production-ml-systems/questions">Production ML systems: Questions to ask | Machine Learning | Google for Developers</a></p>

<h2 id="automated-machine-learning" id="automated-machine-learning">Automated machine learning</h2>

<h3 id="introduction-1" id="introduction-1">Introduction</h3>

<p><strong>AutoML</strong> automates tasks in the machine learning workflow, such as data engineering (feature selection and engineering), training (algorithm selection and hyperparameter tuning), and analysis, making model building faster and easier.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/ml-workflow.png" alt="ml-workflow.png"/></p>

<p>While manual training involves writing code and iteratively adjusting it, AutoML reduces repetitive work and the need for specialised skills.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/automl">Automated Machine Learning (AutoML) | Google for Developers</a></p>

<h3 id="benefits-and-limitations" id="benefits-and-limitations">Benefits and limitations</h3>

<p><strong>Benefits:</strong></p>
<ul><li>To save time.</li>
<li>To improve the quality of an ML model.</li>
<li>To build an ML model without needing specialised skills.</li>
<li>To smoke test a dataset. AutoML can give quick baseline estimates of whether a dataset has enough signal relative to noise.</li>
<li>To evaluate a dataset. AutoML can help determine which features may be worth using.</li>
<li>To enforce best practices. Automation includes built-in support for applying ML best practices.</li></ul>

<p><strong>Limitations:</strong></p>
<ul><li>Model quality may not match that of manual training.</li>
<li>Model search and complexity can be opaque. Models generated with AutoML are difficult to reproduce manually.</li>
<li>Multiple AutoML runs may show greater variance.</li>
<li>Models cannot be customised during training.</li></ul>

<p>Large amounts of data are generally required for AutoML, although specialised systems using <strong>transfer learning</strong> (taking a model trained on one task and adapting its learned representations to a different but related task) can reduce this requirement.</p>

<p><strong>AutoML</strong> suits teams with limited ML experience or those seeking productivity gains without customisation needs. <strong>Custom (manual) training</strong> suits cases where model quality and customisation matter most.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/automl/benefits-limitations">AutoML: Benefits and limitations | Machine Learning | Google for Developers</a></p>

<h3 id="getting-started" id="getting-started">Getting started</h3>

<p>AutoML tools fall into <strong>two categories</strong>:</p>
<ul><li>Tools that require no coding.</li>
<li>API and CLI tools.</li></ul>

<p>The AutoML workflow follows steps similar to traditional machine learning, including problem definition, data gathering, preparation, model development, evaluation, and potential retraining.</p>
<ul><li>Some AutoML systems also support model deployment.</li></ul>

<p><strong>Data preparation</strong> is crucial for AutoML and involves labelling, cleaning and formatting data, and applying feature transformations.</p>

<p>No-code AutoML tools guide users through <strong>model development</strong> with steps such as data import, analysis, refinement, and configuration of run parameters before starting the automated training process.</p>
<ul><li>Users still need to carry out semantic checks to select the appropriate semantic type for each feature (for example recognising that postal codes are categorical rather than numeric), and to set transformations accordingly.</li></ul>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/automl/getting-started">AutoML: Getting started | Machine Learning | Google for Developers</a></p>

<h2 id="fairness" id="fairness">Fairness</h2>

<h3 id="introduction-2" id="introduction-2">Introduction</h3>

<p>Before putting a model into production, it is critical to audit training data and evaluate predictions for bias.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/fairness">Fairness | Machine Learning | Google for Developers</a></p>

<h3 id="types-of-bias" id="types-of-bias">Types of bias</h3>

<p>Machine learning models can be susceptible to <strong>bias</strong> due to human involvement in data selection and curation.</p>

<p>Understanding common human biases is crucial for mitigating their impact on model predictions.</p>

<p>Types of bias include reporting bias, historical bias, automation bias, selection bias, coverage bias, non-response bias, sampling bias, group attribution bias (in-group bias and out-group homogeneity bias), implicit bias, confirmation bias, and experimenter&#39;s bias, <a href="https://wikipedia.org/wiki/List_of_cognitive_biases">among others</a>.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/fairness/types-of-bias">Fairness: Types of bias | Machine Learning | Google for Developers</a></p>

<h3 id="identifying-bias" id="identifying-bias">Identifying bias</h3>

<p><strong>Missing</strong> or <strong>unexpected feature values</strong> in a dataset can indicate potential sources of bias.</p>

<p>Data skew, where certain groups are under- or over-represented, can introduce bias and should be addressed.</p>

<p>Evaluating model performance by subgroup ensures fairness and equal performance across different characteristics.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/fairness/identifying-bias">Fairness: Identifying bias | Machine Learning | Google for Developers</a></p>

<h3 id="mitigating-bias" id="mitigating-bias">Mitigating bias</h3>

<p>Machine learning engineers use two primary strategies to mitigate bias in models:</p>
<ul><li>Augmenting training data.</li>
<li>Adjusting the model&#39;s loss function.</li></ul>

<p><strong>Augmenting training data</strong> involves collecting additional data to address missing, incorrect, or skewed data, but it can be infeasible due to data availability or resource constraints.</p>

<p><strong>Adjusting the model&#39;s loss function</strong> involves using fairness-aware optimisation functions rather than the common default log loss.</p>

<p>The TensorFlow Model Remediation Library provides optimisation functions designed to penalise errors in a fairness-aware manner:</p>
<ul><li><strong>MinDiff</strong> aims to balance errors between different data slices by penalising differences in prediction distributions.</li>
<li><strong>Counterfactual Logit Pairing (CLP)</strong> penalises discrepancies in predictions for similar examples with different sensitive attribute values.</li></ul>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/fairness/mitigating-bias">Fairness: Mitigating bias | Machine Learning | Google for Developers</a></p>

<h3 id="evaluating-for-bias" id="evaluating-for-bias">Evaluating for bias</h3>

<p>Aggregate model performance metrics such as precision, recall, and accuracy can hide biases against minority groups.</p>

<p>Fairness in model evaluation involves ensuring equitable outcomes across different demographic groups.</p>

<p><strong>Fairness metrics</strong> can help assess model predictions for bias.</p>
<ul><li>Demographic parity</li>
<li>Equality of opportunity</li>
<li>Counterfactual fairness</li></ul>

<p>Candidate pool of 100 students: 80 students belong to the majority group (blue), and 20 students belong to the minority group (orange):
<img src="https://media.portblue.net/resources/251229_ml-crash-course/fairness_metrics_candidate_pool.png" alt="fairness_metrics_candidate_pool.png"/></p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/fairness/evaluating-for-bias">Fairness: Evaluating for bias | Machine Learning | Google for Developers</a></p>

<h4 id="demographic-parity" id="demographic-parity">Demographic parity</h4>

<p>Demographic parity aims to <strong>ensure equal acceptance rates for majority and minority groups</strong>, regardless of individual qualifications.</p>

<p>Both the majority (blue) and minority (orange) groups have an acceptance rate of 20%:
<img src="https://media.portblue.net/resources/251229_ml-crash-course/fairness_metrics_demographic_parity.png" alt="fairness_metrics_demographic_parity.png"/></p>

<p>While demographic parity promotes equal representation, it <strong>can overlook differences in individual qualifications</strong> within each group, potentially leading to unfair outcomes.</p>

<p>Qualified students in both groups are shaded in green, and qualified students who were rejected are marked with an X:
<img src="https://media.portblue.net/resources/251229_ml-crash-course/fairness_metrics_demographic_parity_by_qualifications.png" alt="fairness_metrics_demographic_parity_by_qualifications.png"/></p>

<p>Majority acceptance rate = Qualified majority accepted / Qualified majority = 16/35 = 46%
Minority acceptance rate = Qualified minority accepted / Qualified minority = 4/15 = 27%</p>

<p>When the distribution of a preferred label (“qualified”) differs substantially between groups, demographic parity may not be the most appropriate fairness metric.</p>

<p>There may be additional benefits/drawbacks of demographic parity not discussed here that are also worth considering.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/fairness/demographic-parity">Fairness: Demographic parity | Machine Learning | Google for Developers</a></p>

<h4 id="equality-of-opportunity" id="equality-of-opportunity">Equality of opportunity</h4>

<p>Equality of opportunity focuses on <strong>ensuring that qualified individuals have an equal chance of acceptance</strong>, regardless of demographic group.</p>

<p>Qualified students in both groups are shaded in green:
<img src="https://media.portblue.net/resources/251229_ml-crash-course/fairness_metrics_equality_of_opportunity_by_qualifications.png" alt="fairness_metrics_equality_of_opportunity_by_qualifications.png"/></p>

<p>Majority acceptance rate = Qualified majority accepted / Qualified majority = 14/35 = 40%
Minority acceptance rate = Qualified minority accepted / Qualified minority = 6/15 = 40%</p>

<p>Equality of opportunity has limitations, including reliance on a clearly defined preferred label and challenges in settings that lack demographic data.</p>

<p>It is <strong>possible for a model to satisfy both demographic parity and equality of opportunity</strong> under specific conditions where positive prediction rates and true positive rates align across groups.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/fairness/equality-of-opportunity">Fairness: Equality of opportunity | Machine Learning | Google for Developers</a></p>

<h4 id="counterfactual-fairness" id="counterfactual-fairness">Counterfactual fairness</h4>

<p>Counterfactual fairness evaluates fairness by <strong>comparing predictions for similar individuals</strong> who differ only in a sensitive attribute such as demographic group.</p>

<p>This metric is particularly useful when datasets lack complete demographic information for most examples but contain it for a subset.</p>

<p>Candidate pool, with demographic group membership unknown for most candidates (icons shaded in grey):
<img src="https://media.portblue.net/resources/251229_ml-crash-course/fairness_metrics_counterfactual_satisfied.png" alt="fairness_metrics_counterfactual_satisfied.png"/></p>

<p>Counterfactual fairness may not capture broader systemic biases across subgroups. Other fairness metrics, such as demographic parity and equality of opportunity, provide a more holistic view but may require complete demographic data.</p>

<p><strong>Summary</strong></p>

<p>Selecting the appropriate fairness metric depends on the specific application and desired outcome, with no single “right” metric universally applicable.</p>

<p>For example, if the goal is to achieve equal representation, demographic parity may be the optimal metric. If the goal is to achieve equal opportunity, equality of opportunity may be the best metric.</p>

<p>Some definitions of fairness are mutually incompatible.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/fairness/counterfactual-fairness">Fairness: Counterfactual fairness | Machine Learning | Google for Developers</a></p>
]]></content:encoded>
      <guid>https://stefan.angrick.me/google-ml-crash-course-4-notes-real-world-ml</guid>
      <pubDate>Mon, 29 Dec 2025 10:04:59 +0000</pubDate>
    </item>
    <item>
      <title>Google ML Crash Course #3 Notes: Advanced ML Models</title>
      <link>https://stefan.angrick.me/google-ml-crash-course-3-notes-advanced-ml-models?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[This post is part of a four-part summary of Google&#39;s Machine Learning Crash Course. For context, check out this post. This third module covers advanced ML model architectures.!--more--&#xA;&#xA;Neural networks&#xA;&#xA;Introduction&#xA;&#xA;Neural networks are a model architecture designed to automatically identify non-linear patterns in data, eliminating the need for manual feature cross experimentation.&#xA;&#xA;Source: Neural networks | Machine Learning | Google for Developers&#xA;&#xA;Nodes and hidden layers&#xA;&#xA;In neural network terminology, additional layers between the input layer and the output layer are called hidden layers, and the nodes in these layers are called neurons.&#xA;HiddenLayerBigPicture.png&#xA;&#xA;Source: Neural networks: Nodes and hidden layers | Machine Learning | Google for Developers&#xA;&#xA;Activation functions&#xA;&#xA;Each neuron in a neural network performs the following two-step action:&#xA;&#xA;Calculates the weighted sum of input values.&#xA;Applies an activation function to that sum.&#xA;&#xA;Common activation functions include sigmoid, tanh, and ReLU.&#xA;&#xA;The sigmoid function maps input x to an output value between 0 and 1:&#xA;$$&#xA;F(x) = \frac{1}{1 + e^{-x}}&#xA;$$&#xA;sigmoid.png&#xA;&#xA;The tanh function (short for &#34;hyperbolic tangent&#34;) maps input x to an output value between -1 and 1:&#xA;$$&#xA;F(x) = \tanh{(x)}&#xA;$$&#xA;tanh.png&#xA;&#xA;The rectified linear unit activation function (or ReLU, for short) applies a simple rule:&#xA;&#xA;If the input value is less than 0, return 0.&#xA;If the input value is greater than or equal to 0, return the input value.&#xA;$$&#xA;F(x) = \max{(0,x)}&#xA;$$&#xA;&#xA;ReLU often outperforms sigmoid and tanh because it reduces vanishing gradient issues and requires less computation.&#xA;relu.png&#xA;&#xA;A neural network consists of:&#xA;&#xA;A set of nodes, analogous to neurons, organised in layers.&#xA;A set of learned weights and biases connecting layers.&#xA;Activation functions that transform each node&#39;s output, which may differ across layers.&#xA;&#xA;Source: Neural networks: Activation functions | Machine Learning | Google for Developers&#xA;&#xA;Training using backpropagation&#xA;&#xA;Backpropagation is the primary training algorithm for neural networks. It calculates how much each weight and bias in the network contributed to the overall prediction error by applying the chain rule of calculus. It works backwards from the output layer to tell the gradient descent algorithm which equations to adjust to reduce loss.&#xA;&#xA;In practice, this involves a forward pass, where the network makes a prediction and the loss function measures the error, followed by a backward pass that propagates that error back through the layers to compute gradients for each parameter.&#xA;&#xA;Best practices for neural network training:&#xA;&#xA;Vanishing gradients occur when gradients in earlier layers become very small, slowing or stalling training, and can be mitigated by using the ReLU activation function.&#xA;Exploding gradients happen when large weights cause excessively large gradients in early layers, disrupting convergence, and can be addressed with batch normalisation or by lowering the learning rate.&#xA;Dead ReLU units emerge when a ReLU unit&#39;s output gets stuck at 0, halting gradient flow during backpropagation, and can be avoided by lowering the learning rate or using ReLU variants like LeakyReLU.&#xA;Dropout regularisation is a technique to prevent overfitting by randomly dropping unit activations in a network for a single gradient step, with higher dropout rates indicating stronger regularisation (0 = no regularisation, 1 = drop out all nodes).&#xA;&#xA;Source: Neural Networks: Training using backpropagation | Machine Learning | Google for Developers&#xA;&#xA;Multi-class classification&#xA;&#xA;Multi-class classification models predict from multiple possibilities (binary classification models predict just two).&#xA;&#xA;Multi-class classification can be achieved through two main approaches:&#xA;&#xA;One-vs.-all&#xA;One-vs.-one (softmax)&#xA;&#xA;One-vs.-all uses multiple binary classifiers, one for each possible outcome, to determine the probability of each class independently.&#xA;onevsallbinaryclassifiers.png&#xA;&#xA;This approach is fairly reasonable when the total number of classes is small.&#xA;&#xA;We can create a more efficient one-vs.-all model with a deep neural network in which each output node represents a different class.&#xA;onevsallneuralnet.png&#xA;&#xA;Note that the probabilities do not sum to 1. With a one-vs.-all approach, the probability of each binary set of outcomes is determined independently of all the other sets (the sigmoid function is applied to each output node independently).&#xA;&#xA;One-vs.-one (softmax) predicts probabilities of each class relative to all other classes, ensuring all probabilities sum to 1 using the softmax function in the output layer. It assigns decimal probabilities to each class such that all probabilities add up to 1.0. This additional constraint helps training converge more quickly.&#xA;&#xA;Note that the softmax layer must have the same number of nodes as the output layer.&#xA;onevsoneneuralnet.png&#xA;&#xA;The softmax formula extends logistic regression to multiple classes:&#xA;$$&#xA;p(y = j|\textbf{x}) = \frac{e^{(\textbf{w}\j^{T}\textbf{x} + b\j)}}{\sum\{k\in K} e^{(\textbf{w}\k^{T}\textbf{x} + b\k)}}&#xA;$$&#xA;&#xA;Full softmax is fairly cheap when the number of classes is small but can become computationally expensive with many classes.&#xA;&#xA;Candidate sampling offers an alternative for increased efficiency. It computes probabilities for all positive labels but only a random sample of negative labels. For example, if we are interested in determining whether an input image is a beagle or a bloodhound, we do not have to provide probabilities for every non-dog example.&#xA;&#xA;One label versus many labels&#xA;&#xA;Softmax assumes that each example is a member of exactly one class. Some examples, however, can simultaneously be a member of multiple classes. For multi-label problems, use multiple independent logistic regressions instead.&#xA;&#xA;Example: To classify dog breeds from images, including mixed-breed dogs, use one-vs.-all, since it predicts each breed independently and can assign high probabilities to multiple breeds, unlike softmax, which forces probabilities to sum to 1.&#xA;&#xA;Source: Neural networks: Multi-class classification | Machine Learning | Google for Developers&#xA;&#xA;Embeddings&#xA;&#xA;Introduction&#xA;&#xA;Embeddings are lower-dimensional representations of sparse data that address problems associated with one-hot encodings.&#xA;&#xA;A one-hot encoded feature &#34;meal&#34; of 5,000 popular meal items:&#xA;foodimagesonehotencodings.png&#xA;&#xA;This representation of data has several problems:&#xA;&#xA;Large input vectors mean a huge number of weights for a neural network.&#xA;The more weights in your model, the more data you need to train effectively.&#xA;The more weights, the more computation required to train and use the model.&#xA;The more weights in your model, the more memory is needed on the accelerators that train and serve it.&#xA;Poor suitability for on-device machine learning (ODML).&#xA;&#xA;Embeddings, lower-dimensional representations of sparse data, address these issues.&#xA;&#xA;Source: Embeddings | Machine Learning | Google for Developers&#xA;&#xA;Embedding space and static embeddings&#xA;&#xA;Embeddings are low-dimensional representations of high-dimensional data, often used to capture semantic relationships between items.&#xA;&#xA;Embeddings place similar items closer together in the embedding space, allowing for efficient machine learning on large datasets.&#xA;&#xA;Example of a 1D embedding of a sparse feature vector representing meal items:&#xA;embeddings1D.png&#xA;&#xA;2D embedding:&#xA;embeddings2D.png&#xA;&#xA;3D embedding:&#xA;embeddings3Dtangyuan.png&#xA;&#xA;Distances in the embedding space represent relative similarity between items.&#xA;&#xA;Real-world embeddings can encode complex relationships, such as those between countries and their capitals, allowing models to detect patterns.&#xA;&#xA;In practice, embedding spaces have many more than three dimensions, although far fewer than the original data, and the meaning of individual dimensions is often unclear.&#xA;&#xA;Embeddings usually are task-specific, but one task with broad applicability is predicting the context of a word.&#xA;&#xA;Static embeddings like word2vec represent all meanings of a word with a single point, which can be a limitation in some cases. When each word or data point has a single embedding vector, this is called a static embedding.&#xA;&#xA;word2vec can refer both to an algorithm for obtaining static word embeddings and to a set of word vectors that were pre-trained with that algorithm.&#xA;&#xA;Source: Embeddings: Embedding space and static embeddings | Machine Learning | Google for Developers&#xA;&#xA;Obtaining embeddings&#xA;&#xA;Embeddings can be created using dimensionality reduction techniques such as PCA or by training them as part of a neural network.&#xA;&#xA;Training an embedding within a neural network allows customisation for specific tasks, where the embedding layer learns optimal weights to represent data in a lower-dimensional space, but it may take longer than training the embedding separately.&#xA;&#xA;In general, you can create a hidden layer of size d in your neural network that is designated as the embedding layer, where d represents both the number of nodes in the hidden layer and the number of dimensions in the embedding space.&#xA;onehothotdogembedding.png&#xA;&#xA;Word embeddings, such as word2vec, leverage the distributional hypothesis to map semantically similar words to geometrically close vectors. However, such static word embeddings have limitations because they assign a single representation per word.&#xA;&#xA;Contextual embeddings offer multiple representations based on context. For example, &#34;orange&#34; would have a different embedding for every unique sentence containing the word in the dataset (as it could be used as a colour or a fruit).&#xA;&#xA;Contextual embeddings encode positional information, while static embeddings do not. Because contextual embeddings incorporate positional information, one token can have multiple contextual embedding vectors. Static embeddings allow only a single representation of each token.&#xA;&#xA;Methods for creating contextual embeddings include ELMo, BERT, and transformer models with a self-attention layer.&#xA;&#xA;Source: Embeddings: Obtaining embeddings | Machine Learning | Google for Developers&#xA;&#xA;Large language models&#xA;&#xA;Introduction&#xA;&#xA;A language model estimates the probability of a token or sequence of tokens given surrounding text, enabling tasks such as text generation, translation, and summarisation.&#xA;&#xA;Tokens, the atomic units of language modelling, represent words, subwords, or characters and are crucial for understanding and processing language.&#xA;&#xA;Example: &#34;unwatched&#34; would be split into three tokens: un (the prefix), watch (the root), ed (the suffix).&#xA;&#xA;N-grams are ordered sequences of words used to build language models, where N is the number of words in the sequence.&#xA;&#xA;Short N-grams capture too little information, while very long N-grams fail to generalise due to insufficient repeated examples in training data (sparsity issues).&#xA;&#xA;Recurrent neural networks improve on N-grams by processing sequences token by token and learning which past information to retain or discard, allowing them to model longer dependencies across sentences and gain more context.&#xA;&#xA;Note that training recurrent neural networks for long contexts is constrained by the vanishing gradient problem.&#xA;&#xA;Model performance depends on training data size and diversity.&#xA;&#xA;While recurrent neural networks improve context understanding compared to N-grams, they have limitations, paving the way for the emergence of large language models that evaluate the whole context simultaneously.&#xA;&#xA;Source: Large language models | Machine Learning | Google for Developers&#xA;&#xA;What&#39;s a large language model?&#xA;&#xA;Large language models (LLMs) predict sequences of tokens and outperform previous models because they use far more parameters and exploit much wider context.&#xA;&#xA;Transformers form the dominant architecture for LLMs and typically combine an encoder that converts input text into an intermediate representation with a decoder that generates output text, for example translating between languages.&#xA;TransformerBasedTranslator.png&#xA;&#xA;Partial transformers&#xA;&#xA;Encoder-only models focus on representation learning and embeddings (which may serve as input for another system), while decoder-only models specialise in generating long sequences such as dialogue or text continuations.&#xA;&#xA;Self-attention allows the model to weigh the importance of different words in relation to each other, enhancing context understanding.&#xA;&#xA;Example: &#34;The animal didn&#39;t cross the street because it was too tired.&#34;&#xA;&#xA;The self-attention mechanism determines the relevance of each nearby word to the pronoun &#34;it&#34;. The bluer the line, the more important that word is to the pronoun it. As shown, &#34;animal&#34; is more important than &#34;street&#34; to the pronoun &#34;it&#34;.&#xA;Theanimaldidntcrossthestreet.png&#xA;&#xA;Some self-attention mechanisms are bidirectional, meaning they calculate relevance scores for tokens preceding and following the word being attended to. This is useful for generating representations of whole sequences (encoders).&#xA;By contrast, a unidirectional self-attention mechanism can gather context only from words on one side of the word being attended to. This suits applications that generate sequences token by token (decoders).&#xA;&#xA;Multi-head multi-layer self-attention&#xA;&#xA;Each self-attention layer contains multiple self-attention heads. The output of a layer is a mathematical operation (such as a weighted average or dot product) of the outputs of the different heads.&#xA;&#xA;A complete transformer model stacks multiple self-attention layers. The output from one layer becomes the input for the next, allowing the model to build increasingly complex representations, from basic syntax to more nuanced concepts.&#xA;&#xA;Self-attention is an O(N^2  S  D) problem.&#xA;&#xA;N is the number of tokens in the context.&#xA;S is the number of self-attention layers.&#xA;D is the number of heads per layer.&#xA;&#xA;LLMs are trained using masked predictions on massive datasets, enabling them to learn patterns and generate text based on probabilities. You probably will never train an LLM from scratch.&#xA;&#xA;Instruction tuning can improve an LLM&#39;s ability to follow instructions.&#xA;&#xA;Why transformers are so large&#xA;&#xA;This course generally recommends building models with a smaller number of parameters, but research shows that transformers with more parameters consistently achieve better performance.&#xA;&#xA;Text generation&#xA;&#xA;LLMs generate text by repeatedly predicting the most probable next token, effectively acting as highly powerful autocomplete systems. You can think of a user&#39;s question to an LLM as the &#34;given&#34; sentence followed by a masked response.&#xA;&#xA;Benefits and problems&#xA;&#xA;While LLMs offer benefits such as clear text generation, they also present challenges.&#xA;&#xA;Training an LLM involves gathering enormous training sets, consuming vast computational resources and electricity, and solving parallelism challenges.&#xA;Using an LLM for inference raises issues such as hallucinations, high computational and electricity costs, and bias.&#xA;&#xA;Source: LLMs: What&#39;s a large language model? | Machine Learning | Google for Developers&#xA;&#xA;Fine-tuning, distillation, and prompt engineering&#xA;&#xA;General-purpose LLMs, also known as foundation LLMs, base LLMs, or pre-trained LLMs, are pre-trained on vast amounts of text, enabling them to understand language structure and generate creative content, but they act as platforms rather than complete solutions for tasks such as classification or regression.&#xA;&#xA;Fine-tuning updates the parameters of a model to improve its performance on a specialised task, improving prediction quality.&#xA;&#xA;Adapts a foundation LLM to a specific task by training on task-specific examples, often only hundreds or thousands, which improves performance for that task but retains the original model size (same number of parameters) and can still be computationally expensive.&#xA;Parameter-efficient tuning reduces fine-tuning costs by updating only a subset of model parameters during training rather than all weights and biases.&#xA;&#xA;Distillation aims to reduce model size, typically at the cost of some prediction quality.&#xA;&#xA;Distillation compresses an LLM into a smaller student model that runs faster and uses fewer resources, at the cost of some predictive accuracy.&#xA;It typically uses a large teacher model to label data, often with rich numerical scores rather than simple labels, and trains a smaller student model on those outputs.&#xA;&#xA;Prompt engineering allows users to customise an LLM&#39;s output by providing examples or instructions within the prompt, leveraging the model&#39;s existing pattern-recognition abilities without changing its parameters.&#xA;&#xA;One-shot, few-shot, and zero-shot prompting differ by how many examples the prompt provides, with more examples usually improving reliability by giving clearer context.&#xA;&#xA;Prompt engineering does not alter the model&#39;s parameters. Prompts leverage the pattern-recognition abilities of the existing LLM.&#xA;&#xA;Offline inference pre-computes and caches LLM predictions for tasks where real-time response is not critical, saving resources and enabling the use of larger models.&#xA;&#xA;Responsible use of LLMs requires awareness that models inherit biases from their training and distillation data.&#xA;&#xA;Source: LLMs: Fine-tuning, distillation, and prompt engineering | Machine Learning | Google for Developers]]&gt;</description>
      <content:encoded><![CDATA[<p>This post is part of a four-part summary of Google&#39;s <a href="https://developers.google.com/machine-learning/crash-course/">Machine Learning Crash Course</a>. For context, check out <a href="notes-from-googles-machine-learning-crash-course">this post</a>. This third module covers advanced ML model architectures.</p>

<h2 id="neural-networks" id="neural-networks">Neural networks</h2>

<h3 id="introduction" id="introduction">Introduction</h3>

<p>Neural networks are a model architecture designed to automatically identify non-linear patterns in data, eliminating the need for manual feature cross experimentation.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/neural-networks">Neural networks | Machine Learning | Google for Developers</a></p>

<h3 id="nodes-and-hidden-layers" id="nodes-and-hidden-layers">Nodes and hidden layers</h3>

<p>In neural network terminology, additional layers between the input layer and the output layer are called <strong>hidden layers</strong>, and the nodes in these layers are called <strong>neurons</strong>.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/HiddenLayerBigPicture.png" alt="HiddenLayerBigPicture.png"/></p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/neural-networks/nodes-hidden-layers">Neural networks: Nodes and hidden layers | Machine Learning | Google for Developers</a></p>

<h3 id="activation-functions" id="activation-functions">Activation functions</h3>

<p>Each <strong>neuron</strong> in a neural network performs the following two-step action:</p>
<ul><li>Calculates the weighted sum of input values.</li>
<li>Applies an activation function to that sum.</li></ul>

<p>Common activation functions include sigmoid, tanh, and ReLU.</p>

<p>The <strong>sigmoid function</strong> maps input x to an output value <strong>between 0 and 1</strong>:
$$
F(x) = \frac{1}{1 + e^{-x}}
$$
<img src="https://media.portblue.net/resources/251229_ml-crash-course/sigmoid.png" alt="sigmoid.png"/></p>

<p>The <strong>tanh function</strong> (short for “hyperbolic tangent”) maps input x to an output value <strong>between -1 and 1</strong>:
$$
F(x) = \tanh{(x)}
$$
<img src="https://media.portblue.net/resources/251229_ml-crash-course/tanh.png" alt="tanh.png"/></p>

<p>The <strong>rectified linear unit activation function</strong> (or <strong>ReLU</strong>, for short) applies a simple rule:</p>
<ul><li>If the input value is less than 0, return 0.</li>
<li>If the input value is greater than or equal to 0, return the input value.
$$
F(x) = \max{(0,x)}
$$</li></ul>

<p>ReLU often outperforms sigmoid and tanh because it reduces <strong>vanishing gradient issues</strong> and requires less computation.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/relu.png" alt="relu.png"/></p>

<p>A neural network consists of:</p>
<ul><li>A set of nodes, analogous to neurons, organised in layers.</li>
<li>A set of learned weights and biases connecting layers.</li>
<li>Activation functions that transform each node&#39;s output, which may differ across layers.</li></ul>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/neural-networks/activation-functions">Neural networks: Activation functions | Machine Learning | Google for Developers</a></p>

<h3 id="training-using-backpropagation" id="training-using-backpropagation">Training using backpropagation</h3>

<p><strong>Backpropagation</strong> is the primary training algorithm for neural networks. It calculates how much each weight and bias in the network contributed to the overall prediction error by applying the chain rule of calculus. It works backwards from the output layer to tell the gradient descent algorithm which equations to adjust to reduce loss.</p>

<p>In practice, this involves a forward pass, where the network makes a prediction and the loss function measures the error, followed by a backward pass that propagates that error back through the layers to compute gradients for each parameter.</p>

<p>Best practices for neural network training:</p>
<ul><li><strong>Vanishing gradients</strong> occur when gradients in earlier layers become very small, slowing or stalling training, and can be mitigated by using the ReLU activation function.</li>
<li><strong>Exploding gradients</strong> happen when large weights cause excessively large gradients in early layers, disrupting convergence, and can be addressed with batch normalisation or by lowering the learning rate.</li>
<li><strong>Dead ReLU units</strong> emerge when a ReLU unit&#39;s output gets stuck at 0, halting gradient flow during backpropagation, and can be avoided by lowering the learning rate or using ReLU variants like LeakyReLU.</li>
<li><strong>Dropout regularisation</strong> is a technique to prevent overfitting by randomly dropping unit activations in a network for a single gradient step, with higher dropout rates indicating stronger regularisation (0 = no regularisation, 1 = drop out all nodes).</li></ul>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/neural-networks/backpropagation">Neural Networks: Training using backpropagation | Machine Learning | Google for Developers</a></p>

<h3 id="multi-class-classification" id="multi-class-classification">Multi-class classification</h3>

<p><strong>Multi-class classification</strong> models predict from multiple possibilities (binary classification models predict just two).</p>

<p>Multi-class classification can be achieved through two main approaches:</p>
<ul><li>One-vs.-all</li>
<li>One-vs.-one (softmax)</li></ul>

<p><strong>One-vs.-all</strong> uses multiple binary classifiers, one for each possible outcome, to determine the probability of each class independently.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/one_vs_all_binary_classifiers.png" alt="one_vs_all_binary_classifiers.png"/></p>

<p>This approach is fairly reasonable when the total number of classes is small.</p>

<p>We can create a more efficient one-vs.-all model with a deep neural network in which each output node represents a different class.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/one_vs_all_neural_net.png" alt="one_vs_all_neural_net.png"/></p>

<p>Note that the probabilities do not sum to 1. With a one-vs.-all approach, the probability of each binary set of outcomes is determined independently of all the other sets (the sigmoid function is applied to each output node independently).</p>

<p><strong>One-vs.-one (softmax)</strong> predicts probabilities of each class relative to all other classes, ensuring all probabilities sum to 1 using the softmax function in the output layer. It assigns decimal probabilities to each class such that all probabilities add up to 1.0. This additional constraint helps training converge more quickly.</p>

<p>Note that the softmax layer must have the same number of nodes as the output layer.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/one_vs_one_neural_net.png" alt="one_vs_one_neural_net.png"/></p>

<p>The softmax formula extends logistic regression to multiple classes:
$$
p(y = j|\textbf{x}) = \frac{e^{(\textbf{w}_j^{T}\textbf{x} + b_j)}}{\sum_{k\in K} e^{(\textbf{w}_k^{T}\textbf{x} + b_k)}}
$$</p>

<p>Full softmax is fairly cheap when the number of classes is small but can become computationally expensive with many classes.</p>

<p><strong>Candidate sampling</strong> offers an alternative for increased efficiency. It computes probabilities for all positive labels but only a random sample of negative labels. For example, if we are interested in determining whether an input image is a beagle or a bloodhound, we do not have to provide probabilities for every non-dog example.</p>

<p><strong>One label versus many labels</strong></p>

<p>Softmax assumes that each example is a member of exactly one class. Some examples, however, can simultaneously be a member of multiple classes. For multi-label problems, use multiple independent logistic regressions instead.</p>

<p><strong>Example:</strong> To classify dog breeds from images, including mixed-breed dogs, use one-vs.-all, since it predicts each breed independently and can assign high probabilities to multiple breeds, unlike softmax, which forces probabilities to sum to 1.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/neural-networks/multi-class">Neural networks: Multi-class classification | Machine Learning | Google for Developers</a></p>

<h2 id="embeddings" id="embeddings">Embeddings</h2>

<h3 id="introduction-1" id="introduction-1">Introduction</h3>

<p><strong>Embeddings</strong> are lower-dimensional representations of sparse data that address problems associated with one-hot encodings.</p>

<p>A one-hot encoded feature “meal” of 5,000 popular meal items:
<img src="https://media.portblue.net/resources/251229_ml-crash-course/food_images_one_hot_encodings.png" alt="food_images_one_hot_encodings.png"/></p>

<p>This representation of data has several problems:</p>
<ul><li>Large input vectors mean a <strong>huge number of weights</strong> for a neural network.</li>
<li>The more weights in your model, the <strong>more data you need</strong> to train effectively.</li>
<li>The more weights, the <strong>more computation required</strong> to train and use the model.</li>
<li>The more weights in your model, the <strong>more memory is needed</strong> on the accelerators that train and serve it.</li>
<li><strong>Poor suitability for on-device machine learning</strong> (ODML).</li></ul>

<p>Embeddings, lower-dimensional representations of sparse data, address these issues.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/embeddings">Embeddings | Machine Learning | Google for Developers</a></p>

<h3 id="embedding-space-and-static-embeddings" id="embedding-space-and-static-embeddings">Embedding space and static embeddings</h3>

<p><strong>Embeddings</strong> are low-dimensional representations of high-dimensional data, often used to capture <strong>semantic relationships</strong> between items.</p>

<p>Embeddings place similar items closer together in the embedding space, allowing for efficient machine learning on large datasets.</p>

<p>Example of a 1D embedding of a sparse feature vector representing meal items:
<img src="https://media.portblue.net/resources/251229_ml-crash-course/embeddings_1D.png" alt="embeddings_1D.png"/></p>

<p>2D embedding:
<img src="https://media.portblue.net/resources/251229_ml-crash-course/embeddings_2D.png" alt="embeddings_2D.png"/></p>

<p>3D embedding:
<img src="https://media.portblue.net/resources/251229_ml-crash-course/embeddings_3D_tangyuan.png" alt="embeddings_3D_tangyuan.png"/></p>

<p>Distances in the embedding space represent relative similarity between items.</p>

<p><strong>Real-world embeddings</strong> can encode complex relationships, such as those between countries and their capitals, allowing models to detect patterns.</p>

<p>In practice, embedding spaces have many more than three dimensions, although far fewer than the original data, and the meaning of individual dimensions is often unclear.</p>

<p>Embeddings usually are task-specific, but one task with broad applicability is predicting the context of a word.</p>

<p><strong>Static embeddings</strong> like word2vec represent all meanings of a word with a single point, which can be a limitation in some cases. When each word or data point has a single embedding vector, this is called a static embedding.</p>

<p><strong>word2vec</strong> can refer both to an algorithm for obtaining static word embeddings and to a set of word vectors that were pre-trained with that algorithm.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/embeddings/embedding-space">Embeddings: Embedding space and static embeddings | Machine Learning | Google for Developers</a></p>

<h3 id="obtaining-embeddings" id="obtaining-embeddings">Obtaining embeddings</h3>

<p>Embeddings can be created using <strong>dimensionality reduction techniques</strong> such as PCA or by training them as part of a neural network.</p>

<p><strong>Training an embedding within a neural network</strong> allows customisation for specific tasks, where the embedding layer learns optimal weights to represent data in a lower-dimensional space, but it may take longer than training the embedding separately.</p>

<p>In general, you can create a hidden layer of size d in your neural network that is designated as the embedding layer, where d represents both the number of nodes in the hidden layer and the number of dimensions in the embedding space.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/one_hot_hot_dog_embedding.png" alt="one_hot_hot_dog_embedding.png"/></p>

<p>Word embeddings, such as word2vec, leverage the distributional hypothesis to map semantically similar words to geometrically close vectors. However, such static word embeddings have limitations because they assign a single representation per word.</p>

<p><strong>Contextual embeddings</strong> offer multiple representations based on context. For example, “orange” would have a different embedding for every unique sentence containing the word in the dataset (as it could be used as a colour or a fruit).</p>

<p>Contextual embeddings encode positional information, while static embeddings do not. Because contextual embeddings incorporate positional information, one token can have multiple contextual embedding vectors. Static embeddings allow only a single representation of each token.</p>

<p>Methods for creating contextual embeddings include <a href="https://wikipedia.org/wiki/ELMo">ELMo</a>, <a href="https://developers.google.com/machine-learning/glossary#bert-bidirectional-encoder-representations-from-transformers">BERT</a>, and transformer models with a <a href="https://developers.google.com/machine-learning/glossary#self-attention-also-called-self-attention-layer">self-attention</a> layer.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/embeddings/obtaining-embeddings">Embeddings: Obtaining embeddings | Machine Learning | Google for Developers</a></p>

<h2 id="large-language-models" id="large-language-models">Large language models</h2>

<h3 id="introduction-2" id="introduction-2">Introduction</h3>

<p>A <strong>language model</strong> estimates the probability of a token or sequence of tokens given surrounding text, enabling tasks such as text generation, translation, and summarisation.</p>

<p><strong>Tokens</strong>, the atomic units of language modelling, represent words, subwords, or characters and are crucial for understanding and processing language.</p>

<p>Example: “unwatched” would be split into three tokens: un (the prefix), watch (the root), ed (the suffix).</p>

<p><strong>N-grams</strong> are ordered sequences of words used to build language models, where N is the number of words in the sequence.</p>

<p>Short N-grams capture too little information, while very long N-grams fail to generalise due to insufficient repeated examples in training data (sparsity issues).</p>

<p><strong>Recurrent neural networks</strong> improve on N-grams by processing sequences token by token and learning which past information to retain or discard, allowing them to model longer dependencies across sentences and gain more context.</p>
<ul><li>Note that training recurrent neural networks for long contexts is constrained by the vanishing gradient problem.</li></ul>

<p>Model performance depends on training data size and diversity.</p>

<p>While recurrent neural networks improve context understanding compared to N-grams, they have limitations, paving the way for the emergence of <strong>large language models</strong> that evaluate the whole context simultaneously.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/llm">Large language models | Machine Learning | Google for Developers</a></p>

<h3 id="what-s-a-large-language-model" id="what-s-a-large-language-model">What&#39;s a large language model?</h3>

<p><strong>Large language models (LLMs)</strong> predict sequences of tokens and outperform previous models because they use far more parameters and exploit much wider context.</p>

<p><strong>Transformers</strong> form the dominant architecture for LLMs and typically combine an encoder that converts input text into an intermediate representation with a decoder that generates output text, for example translating between languages.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/TransformerBasedTranslator.png" alt="TransformerBasedTranslator.png"/></p>

<p><strong>Partial transformers</strong></p>

<p><strong>Encoder-only models</strong> focus on representation learning and embeddings (which may serve as input for another system), while <strong>decoder-only models</strong> specialise in generating long sequences such as dialogue or text continuations.</p>

<p><strong>Self-attention</strong> allows the model to weigh the importance of different words in relation to each other, enhancing context understanding.</p>

<p>Example: “The animal didn&#39;t cross the street because it was too tired.”</p>

<p>The self-attention mechanism determines the relevance of each nearby word to the pronoun “it”. The bluer the line, the more important that word is to the pronoun it. As shown, “animal” is more important than “street” to the pronoun “it”.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/Theanimaldidntcrossthestreet.png" alt="Theanimaldidntcrossthestreet.png"/></p>
<ul><li>Some self-attention mechanisms are <strong>bidirectional</strong>, meaning they calculate relevance scores for tokens preceding and following the word being attended to. This is useful for generating representations of whole sequences (encoders).</li>
<li>By contrast, a <strong>unidirectional</strong> self-attention mechanism can gather context only from words on one side of the word being attended to. This suits applications that generate sequences token by token (decoders).</li></ul>

<p><strong>Multi-head multi-layer self-attention</strong></p>

<p>Each self-attention layer contains multiple <strong>self-attention heads</strong>. The output of a layer is a mathematical operation (such as a weighted average or dot product) of the outputs of the different heads.</p>

<p>A complete transformer model stacks multiple <strong>self-attention layers</strong>. The output from one layer becomes the input for the next, allowing the model to build increasingly complex representations, from basic syntax to more nuanced concepts.</p>

<p>Self-attention is an O(N^2 * S * D) problem.</p>
<ul><li>N is the number of tokens in the context.</li>
<li>S is the number of self-attention layers.</li>
<li>D is the number of heads per layer.</li></ul>

<p>LLMs are <strong>trained</strong> using masked predictions on massive datasets, enabling them to learn patterns and generate text based on probabilities. You probably will never train an LLM from scratch.</p>

<p>Instruction tuning can improve an LLM&#39;s ability to follow instructions.</p>

<p><strong>Why transformers are so large</strong></p>

<p>This course generally recommends building models with a smaller number of parameters, but research shows that transformers with <strong>more parameters</strong> consistently achieve better performance.</p>

<p><strong>Text generation</strong></p>

<p>LLMs generate text by repeatedly predicting the most probable next token, effectively acting as highly powerful autocomplete systems. You can think of a user&#39;s question to an LLM as the “given” sentence followed by a masked response.</p>

<p><strong>Benefits and problems</strong></p>

<p>While LLMs offer benefits such as clear text generation, they also present challenges.</p>
<ul><li><strong>Training an LLM</strong> involves gathering enormous training sets, consuming vast computational resources and electricity, and solving parallelism challenges.</li>
<li><strong>Using an LLM</strong> for inference raises issues such as hallucinations, high computational and electricity costs, and bias.</li></ul>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/llm/transformers">LLMs: What&#39;s a large language model? | Machine Learning | Google for Developers</a></p>

<h3 id="fine-tuning-distillation-and-prompt-engineering" id="fine-tuning-distillation-and-prompt-engineering">Fine-tuning, distillation, and prompt engineering</h3>

<p>General-purpose LLMs, also known as <strong>foundation LLMs</strong>, base LLMs, or pre-trained LLMs, are pre-trained on vast amounts of text, enabling them to understand language structure and generate creative content, but they act as platforms rather than complete solutions for tasks such as classification or regression.</p>

<p><strong>Fine-tuning</strong> updates the parameters of a model to improve its performance on a specialised task, improving prediction quality.</p>
<ul><li>Adapts a foundation LLM to a specific task by training on task-specific examples, often only hundreds or thousands, which <strong>improves performance for that task</strong> but retains the original model size (same number of parameters) and can still be computationally expensive.</li>
<li>Parameter-efficient tuning reduces fine-tuning costs by updating only a subset of model parameters during training rather than all weights and biases.</li></ul>

<p><strong>Distillation</strong> aims to reduce model size, typically at the cost of some prediction quality.</p>
<ul><li>Distillation compresses an LLM into a smaller student model that runs faster and uses fewer resources, at the <strong>cost of some predictive accuracy</strong>.</li>
<li>It typically uses a large teacher model to label data, often with rich numerical scores rather than simple labels, and trains a smaller student model on those outputs.</li></ul>

<p><strong>Prompt engineering</strong> allows users to customise an LLM&#39;s output by providing examples or instructions within the prompt, leveraging the model&#39;s existing pattern-recognition abilities without changing its parameters.</p>

<p><strong>One-shot</strong>, <strong>few-shot</strong>, and <strong>zero-shot</strong> prompting differ by how many examples the prompt provides, with more examples usually improving reliability by giving clearer context.</p>

<p>Prompt engineering does not alter the model&#39;s parameters. Prompts leverage the pattern-recognition abilities of the existing LLM.</p>

<p><strong>Offline inference</strong> pre-computes and caches LLM predictions for tasks where real-time response is not critical, saving resources and enabling the use of larger models.</p>

<p><strong>Responsible use of LLMs</strong> requires awareness that models inherit biases from their training and distillation data.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/llm/tuning">LLMs: Fine-tuning, distillation, and prompt engineering | Machine Learning | Google for Developers</a></p>
]]></content:encoded>
      <guid>https://stefan.angrick.me/google-ml-crash-course-3-notes-advanced-ml-models</guid>
      <pubDate>Mon, 29 Dec 2025 10:04:16 +0000</pubDate>
    </item>
    <item>
      <title>Google ML Crash Course #2 Notes: Data</title>
      <link>https://stefan.angrick.me/google-ml-crash-course-2-notes-data?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[This post is part of a four-part summary of Google&#39;s Machine Learning Crash Course. For context, check out this post. This second module covers fundamental techniques and best practices for working with machine learning data.!--more--&#xA;&#xA;Working with numerical data&#xA;&#xA;Introduction&#xA;&#xA;Numerical data: Integers or floating-point values that behave like numbers. They are additive, countable, ordered, and so on. Examples include temperature, weight, or the number of deer wintering in a nature preserve.&#xA;&#xA;Source: Working with numerical data | Machine Learning | Google for Developers&#xA;&#xA;How a model ingests data with feature vectors&#xA;&#xA;A machine learning model ingests data through floating-point arrays called feature vectors, which are derived from dataset features. Feature vectors often utilise processed or transformed values instead of raw dataset values to enhance model learning.&#xA;&#xA;Example of a feature vector: [0.13, 0.47]&#xA;&#xA;Feature engineering is the process of converting raw data into suitable representations for the model. Common techniques are:&#xA;&#xA;Normalization: Converting numerical values into a standard range.&#xA;Binning (bucketing): Converting numerical values into buckets or ranges.&#xA;&#xA;Non-numerical data like strings must be converted into numerical values for use in feature vectors.&#xA;&#xA;Source: Numerical data: How a model ingests data using feature vectors | Machine Learning | Google for Developers&#xA;&#xA;First steps&#xA;&#xA;Before creating feature vectors, it is crucial to analyse numerical data to detect anomalies and patterns in the data, which aids in identifying potential issues early in the data analysis process.&#xA;&#xA;Visualising it through plots and graphs (like scatter plots or histograms)&#xA;Calculating basic statistics like mean, median, standard deviation, or values at the quartile divisions (0th, 25th, 50th, 75th, 100th percentiles, where the 50th percentile is the median)&#xA;&#xA;Outliers, values significantly distant from others, should be identified and handled appropriately.&#xA;&#xA;The outlier is due to a mistake: For example, an experimenter incorrectly entered data, or an instrument malfunctioned. We generally delete examples containing mistake outliers.&#xA;If the outlier is a legitimate data point: If the model needs to infer good predictions on these outliers, keep them. If not, delete them or apply more invasive feature engineering techniques, such as clipping.&#xA;&#xA;A dataset probably contains outliers when:&#xA;&#xA;The delta between the 0th and 25th percentiles differs significantly from the delta between the 75th and 100th percentiles&#xA;The standard deviation is almost as high as the mean&#xA;&#xA;Source: Numerical data: First steps | Machine Learning | Google for Developers&#xA;&#xA;Normalization&#xA;&#xA;Data normalization is crucial for enhancing machine learning model performance by scaling features to a similar range. It is also recommended to normalise a single numeric feature that covers a wide range (for example, city population).&#xA;&#xA;Normalisation has the following benefits:&#xA;&#xA;Helps a model converge more quickly.&#xA;Helps models infer better predictions.&#xA;Helps avoid the NaN trap (large numerical values exceeding the floating-point precision limit and flipping into NaN values).&#xA;Helps the model learn appropriate weights (so the model does not pay too much attention to features with wide ranges).&#xA;&#xA;| Normalization technique | Formula                                                | When to use                                                                                      |&#xA;| ----------------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------ |&#xA;| Linear scaling          | $$x&#39;=\frac{x-x\\text{min}}{x\\text{max}-x\\text{min}}$$  | When the feature is mostly uniformly distributed across range; flat-shaped                       |&#xA;| Z-score scaling         | $$x&#39; = (x-\mu)/\sigma$$                                  | When the feature is normally distributed (peak close to mean); bell-shaped                       |&#xA;| Log scaling             | $$x&#39;=ln(x)$$                                             | When the feature distribution is heavy skewed on at least either side of tail; heavy Tail-shaped |&#xA;| Clipping                | If x   max, set $$x&#39;=max$$ If x &lt; min, set $$x&#39; = min$$ | When the feature contains extreme outliers                                                       |&#xA;&#xA;Source: Numerical data: Normalization | Machine Learning | Google for Developers&#xA;&#xA;Binning&#xA;&#xA;Binning (bucketing) is a feature engineering technique used to group numerical data into categories (bins). In many cases, this turns numerical data into categorical data.&#xA;&#xA;For example, if a feature X has values ranging from 15 to 425, we can apply binning to represent X as a feature vector divided into specific intervals:&#xA;&#xA;| Bin number | Range   | Feature vector            |&#xA;| ---------- | ------- | ------------------------- |&#xA;| 1          | 15-34   | [1.0, 0.0, 0.0, 0.0, 0.0] |&#xA;| 2          | 35-117  | [0.0, 1.0, 0.0, 0.0, 0.0] |&#xA;| 3          | 118-279 | [0.0, 0.0, 1.0, 0.0, 0.0] |&#xA;| 4          | 280-392 | [0.0, 0.0, 0.0, 1.0, 0.0] |&#xA;| 5          | 393-425 | [0.0, 0.0, 0.0, 0.0, 1.0] |&#xA;&#xA;Even though X is a single column in the dataset, binning causes a model to treat X as five separate features. Therefore, the model learns separate weights for each bin.&#xA;&#xA;Binning offers an alternative to scaling or clipping and is particularly useful for handling outliers and improving model performance on non-linear data.&#xA;&#xA;When to use: Binning works well when features exhibit a &#34;clumpy&#34; distribution, that is, the overall linear relationship between the feature and label is weak or nonexistent, or when feature values are clustered.&#xA;&#xA;Example: Number of shoppers versus temperature. By binning them, the model learns separate weights for each bin.&#xA;binningtemperaturevsshoppersdividedinto3bins.png&#xA;&#xA;While creating multiple bins is possible, it is generally recommended to avoid an excessive number, as this can lead to insufficient training examples per bin and increased feature dimensionality.&#xA;&#xA;Quantile bucketing is a specific binning technique that ensures each bin contains a roughly equal number of examples, which can be particularly useful for datasets with skewed distributions.&#xA;&#xA;Quantile buckets give extra information space to the large torso while compacting the long tail into a single bucket.&#xA;Equal intervals give extra information space to the long tail while compacting the large torso into a single bucket.&#xA;QuantileBucketing.png&#xA;&#xA;Source: Numerical data: Binning | Machine Learning | Google for Developers&#xA;&#xA;Scrubbing&#xA;&#xA;| Problem category            | Example                                                         |&#xA;| --------------------------- | --------------------------------------------------------------- |&#xA;| Omitted values              | A census taker fails to record a resident&#39;s age                 |&#xA;| Duplicate examples          | A server uploads the same logs twice                            |&#xA;| Out-of-range feature values | A human accidentally types an extra digit                       |&#xA;| Bad labels                  | A human evaluator mislabels a picture of an oak tree as a maple |&#xA;&#xA;You can use programs or scripts to identify and handle data issues such as omitted values, duplicates, and out-of-range feature values by removing or correcting them.&#xA;&#xA;Source: Numerical data: Scrubbing | Machine Learning | Google for Developers&#xA;&#xA;Qualities of good numerical features&#xA;&#xA;Good feature vectors require features that are clearly named and have obvious meanings to anyone on the project.&#xA;Data should be checked and tested for bad data or outliers, such as inappropriate values, before being used for training.&#xA;Features should be sensible, avoiding &#34;magic values&#34; that create discontinuities (for example, setting the value &#34;watch\time\in\seconds&#34; to -1 to indicate an absence of measurement); instead, use separate boolean features or new discrete values to indicate missing data.&#xA;&#xA;Source: Numerical data: Qualities of good numerical features | Machine Learning | Google for Developers&#xA;&#xA;Polynomial transformations&#xA;&#xA;Synthetic features, such as polynomial transforms, enable linear models to represent non-linear relationships by introducing new features based on existing ones.&#xA;&#xA;By incorporating synthetic features, linear regression models can effectively separate data points that are not linearly separable, using curves instead of straight lines. For example, we can separate two classes with y = x^2.&#xA;ftcross1.png&#xA;&#xA;Feature crosses, a related concept for categorical data, synthesise new features by combining existing features, further enhancing model flexibility.&#xA;&#xA;Source: Numerical data: Polynomial transforms | Machine Learning | Google for Developers&#xA;&#xA;Working with categorical data&#xA;&#xA;Introduction&#xA;&#xA;Categorical data has a specific set of possible values. Examples include species of animals, names of streets, whether or not an email is spam, and binned numbers.&#xA;&#xA;Categorical data can include numbers that behave like categories. An example is postal codes.&#xA;&#xA;Numerical data can be meaningfully multiplied.&#xA;Data that are native integer values should be represented as categorical data.&#xA;&#xA;Encoding means converting categorical or other data to numerical vectors that a model can train on.&#xA;&#xA;Preprocessing includes converting non-numerical data, such as strings, to floating-point values.&#xA;&#xA;Source: Working with categorical data | Machine Learning | Google for Developers&#xA;&#xA;Vocabulary and one-hot encoding&#xA;&#xA;Machine learning models require numerical input; therefore, categorical data such as strings must be converted to numerical representations.&#xA;&#xA;The term dimension is a synonym for the number of elements in a feature vector. Some categorical features are low dimensional. For example:&#xA;&#xA;| Feature name | # of categories | Sample categories              |&#xA;| ------------ | --------------- | ------------------------------ |&#xA;| snowedtoday | 2               | True, False                    |&#xA;| skilllevel  | 3               | Beginner, Practitioner, Expert |&#xA;| season       | 4               | Winter, Spring, Summer, Autumn |&#xA;| dayofweek  | 7               | Monday, Tuesday, Wednesday     |&#xA;| planet       | 8               | Mercury, Venus, Earth          |&#xA;| carcolour   | 8               | Red, Orange, Blue, Yellow      |&#xA;&#xA;When a categorical feature has a low number of possible categories, you can encode it as a vocabulary. This treats each category as a separate feature, allowing the model to learn distinct weights for each during training.&#xA;&#xA;One-hot encoding transforms categorical values into numerical vectors (arrays) of N elements, where N is the number of categories. Exactly one of the elements in a one-hot vector has the value 1.0; all the remaining elements have the value 0.0.&#xA;&#xA;| Feature  | Red | Orange | Blue | Yellow | Green | Black | Purple | Brown |&#xA;| -------- | --- | ------ | ---- | ------ | ----- | ----- | ------ | ----- |&#xA;| &#34;Red&#34;    | 1   | 0      | 0    | 0      | 0     | 0     | 0      | 0     |&#xA;| &#34;Orange&#34; | 0   | 1      | 0    | 0      | 0     | 0     | 0      | 0     |&#xA;| &#34;Blue&#34;   | 0   | 0      | 1    | 0      | 0     | 0     | 0      | 0     |&#xA;| &#34;Yellow&#34; | 0   | 0      | 0    | 1      | 0     | 0     | 0      | 0     |&#xA;| &#34;Green&#34;  | 0   | 0      | 0    | 0      | 1     | 0     | 0      | 0     |&#xA;| &#34;Black&#34;  | 0   | 0      | 0    | 0      | 0     | 1     | 0      | 0     |&#xA;| &#34;Purple&#34; | 0   | 0      | 0    | 0      | 0     | 0     | 1      | 0     |&#xA;| &#34;Brown&#34;  | 0   | 0      | 0    | 0      | 0     | 0     | 0      | 1     |&#xA;&#xA;It is the one-hot vector, not the string or the index number, that gets passed to the feature vector. The model learns a separate weight for each element of the feature vector.&#xA;&#xA;The end-to-end process to map categories to feature vectors:&#xA;vocabulary-index-sparse-feature.png&#xA;&#xA;In a true one-hot encoding, only one element has the value 1.0. In a variant known as multi-hot encoding, multiple values can be 1.0.&#xA;&#xA;A feature whose values are predominantly zero (or empty) is termed a sparse feature.&#xA;&#xA;Sparse representation efficiently stores one-hot encoded data by only recording the position of the &#39;1&#39; value to reduce memory usage.&#xA;&#xA;For example, the one-hot vector for &#34;car\colour&#34; &#34;Blue&#34; is: [0, 0, 1, 0, 0, 0, 0, 0].&#xA;Since the 1 is in position 2 (when starting the count at 0), the sparse representation is: 2.&#xA;&#xA;Notice that the sparse representation consumes far less memory. Importantly, the model must train on the one-hot vector, not the sparse representation.&#xA;&#xA;The sparse representation of a multi-hot encoding stores the positions of all the non-zero elements. For example, the sparse representation of a car that is both &#34;Blue&#34; and &#34;Black&#34; is 2, 5.&#xA;&#xA;Categorical features can have outliers. If &#34;car\colour&#34; includes rare values such as &#34;Mauve&#34; or &#34;Avocado&#34;, you can group them into one out-of-vocabulary (OOV) category. All rare colours go into this single bucket, and the model learns one weight for it.&#xA;&#xA;For high-dimensional categorical features with many categories, one-hot encoding might be inefficient, and embeddings or hashing (also called the hashing trick) are recommended.&#xA;&#xA;For example, a feature like &#34;words\in\english&#34; has around 500,000 categories.&#xA;Embeddings substantially reduce the number of dimensions, which helps the model train faster and infer predictions more quickly.&#xA;&#xA;Source: Categorical data: Vocabulary and one-hot encoding | Machine Learning | Google for Developers&#xA;&#xA;Common issues with categorical data&#xA;&#xA;Categorical data quality hinges on how categories are defined and labelled, impacting data reliability.&#xA;&#xA;Human-labelled data, known as &#34;gold labels&#34;, is generally preferred for training due to its higher quality, but it is essential to check for human errors and biases.&#xA;&#xA;Any two human beings may label the same example differently. The difference between human raters&#39; decisions is called inter-rater agreement.&#xA;Inter-rater agreement can be measured using kappa and intra-class correlation (Hallgren, 2012), or Krippendorff&#39;s alpha (Krippendorff, 2011).&#xA;&#xA;Machine-labelled data, or &#34;silver labels&#34;, can introduce biases or inaccuracies, necessitating careful quality checks and awareness of potential common-sense violations.&#xA;&#xA;For example, if a computer-vision model mislabels a photo of a chihuahua as a muffin, or a photo of a muffin as a chihuahua.&#xA;Similarly, a sentiment analyser that scores neutral words as -0.25, when 0.0 is the neutral value, might be scoring all words with an additional negative bias.&#xA;&#xA;High dimensionality in categorical data increases training complexity and costs, leading to techniques such as embeddings for dimensionality reduction.&#xA;&#xA;Source: Categorical data: Common issues | Machine Learning | Google for Developers&#xA;&#xA;Feature crosses&#xA;&#xA;Feature crosses are created by combining two or more categorical or bucketed features to capture interactions and non-linearities within a dataset.&#xA;&#xA;For example, consider a leaf dataset with the categorical features:&#xA;&#xA;&#34;edges&#34;, containing values {smooth, toothed, lobed}&#xA;&#34;arrangement&#34;, containing values {opposite, alternate}&#xA;&#xA;The feature cross, or Cartesian product, of these two features would be:&#xA;&#xA;{Smooth\Opposite, Smooth\Alternate, Toothed\Opposite, Toothed\Alternate, Lobed\Opposite, Lobed\Alternate}&#xA;&#xA;For example, if a leaf has a lobed edge and an alternate arrangement, the feature-cross vector will have a value of 1 for &#34;Lobed\Alternate&#34;, and a value of 0 for all other terms:&#xA;&#xA;{0, 0, 0, 0, 0, 1}&#xA;&#xA;This dataset could be used to classify leaves by tree species, since these characteristics do not vary within a species.&#xA;&#xA;Feature crosses are somewhat analogous to polynomial transforms.&#xA;&#xA;Feature crosses can be particularly effective when guided by domain expertise. It is often possible, though computationally expensive, to use neural networks to automatically find and apply useful feature combinations during training.&#xA;&#xA;Overuse of feature crosses with sparse features should be avoided, as it can lead to excessive sparsity in the resulting feature set. For example, if feature A is a 100-element sparse feature and feature B is a 200-element sparse feature, a feature cross of A and B yields a 20,000-element sparse feature.&#xA;&#xA;Source: Categorical data: Feature crosses | Machine Learning | Google for Developers&#xA;&#xA;Datasets, generalization, and overfitting&#xA;&#xA;Introduction&#xA;&#xA;Data quality significantly impacts model performance more than algorithm choice.&#xA;Machine learning practitioners typically dedicate a substantial portion of their project time (around 80%) to data preparation and transformation, including tasks such as dataset construction and feature engineering.&#xA;&#xA;Source: Datasets, generalization, and overfitting | Machine Learning | Google for Developers&#xA;&#xA;Data characteristics&#xA;&#xA;A machine learning model&#39;s performance is heavily reliant on the quality and quantity of the dataset it is trained on, with larger, high-quality datasets generally leading to better results.&#xA;&#xA;Datasets can contain various data types, including numerical, categorical, text, multimedia, and embedding vectors, each requiring specific handling for optimal model training.&#xA;&#xA;The following are common causes of unreliable data in datasets:&#xA;&#xA;Omitted values&#xA;Duplicate examples&#xA;Bad feature values&#xA;Bad labels&#xA;Bad sections of data&#xA;&#xA;Maintaining data quality involves addressing issues such as label errors, noisy features, and proper filtering to ensure the reliability of the dataset for accurate predictions.&#xA;&#xA;Incomplete examples with missing feature values should be handled by either deletion or imputation to avoid negatively impacting model training.&#xA;&#xA;When imputing missing values, use reliable methods such as mean/median imputation and consider adding an indicator column to signal imputed values to the model. For example, alongside temperature include &#34;temperature\is\imputed&#34;. This lets the model learn to trust real observations more than imputed ones.&#xA;&#xA;Source: Datasets: Data characteristics | Machine Learning | Google for Developers&#xA;&#xA;Labels&#xA;&#xA;Direct labels are generally preferred but often unavailable.&#xA;&#xA;Direct labels exactly match the prediction target and appear explicitly in the dataset, such as a &#34;bicycle\owner&#34; column for predicting bicycle ownership.&#xA;Proxy labels approximate the target and correlate with it, such as a bicycle magazine subscription as a signal of bicycle ownership.&#xA;&#xA;Use a proxy label when no direct label exists or when the direct concept resists easy numeric representation. Carefully evaluate proxy labels to ensure they are a suitable approximation.&#xA;&#xA;Human-generated labels, while offering flexibility and nuanced understanding, can be expensive to produce and prone to errors, requiring careful quality control.&#xA;&#xA;Models can train on a mix of automated and human-generated labels, but an extra set of human labels often adds complexity without sufficient benefit.&#xA;&#xA;Source: Datasets: Labels | Machine Learning | Google for Developers&#xA;&#xA;Imbalanced datasets&#xA;&#xA;Imbalanced datasets occur when one label (majority class) is significantly more frequent than another (minority class), potentially hindering model training on the minority class.&#xA;&#xA;Note: Accuracy is usually a poor metric for assessing a model trained on a class-imbalanced dataset.&#xA;&#xA;A highly imbalanced floral dataset containing far more sunflowers (200) than roses (2):&#xA;FloralDataset200Sunflowers2Roses.png&#xA;&#xA;During training, a model should learn two things:&#xA;&#xA;What each class looks like, that is, what feature values correspond to which class.&#xA;How common each class is, that is, what the relative distribution of the classes is.&#xA;&#xA;Standard training conflates these two goals. In contrast, a two-step technique of downsampling and upweighting the majority class separates these two goals, enabling the model to achieve both.&#xA;&#xA;Step 1: Downsample the majority class by training on only a small fraction of majority class examples, which makes an imbalanced dataset more balanced during training and increases the chance that each batch contains enough minority examples.&#xA;&#xA;For example, with a class-imbalanced dataset consisting of 99% majority class and 1% minority class examples, we could downsample the majority class by a factor of 25 to create a more balanced training set (80% majority class and 20% minority class).&#xA;&#xA;Downsampling the majority class by a factor of 25:&#xA;FloralDatasetDownsampling.png&#xA;&#xA;Step 2: Upweight the downsampled majority class by the same factor used for downsampling, so each majority class error counts proportionally more during training. This corrects the artificial class distribution and bias introduced by downsampling, because the training data no longer reflects real-world frequencies.&#xA;&#xA;Continuing the example from above, we must upweight the majority class by a factor of 25. That is, when the model mistakenly predicts the majority class, treat the loss as if it were 25 errors (multiply the regular loss by 25).&#xA;&#xA;Upweighting the majority class by a factor of 25:&#xA;FloralDatasetUpweighting.png&#xA;&#xA;Experiment with different downsampling and upweighting factors just as you would experiment with other hyperparameters.&#xA;&#xA;Benefits of this technique include a better model (the resultant model knows what each class looks like and how common each class is) and faster convergence.&#xA;&#xA;Source: Datasets: Class-imbalanced datasets | Machine Learning | Google for Developers&#xA;&#xA;Dividing the original dataset&#xA;&#xA;Machine learning models should be tested against unseen data.&#xA;&#xA;It is recommended to split the dataset into three subsets: training, validation, and test sets.&#xA;PartitionThreeSets.png&#xA;&#xA;The validation set is used for initial testing during training (to determine hyperparameter tweaks, add, remove, or transform features, and so on), and the test set is used for final evaluation.&#xA;workflowwithvalidationset.png&#xA;&#xA;The validation and test sets can &#34;wear out&#34; with repeated use. For this reason, it is a good idea to collect more data to &#34;refresh&#34; the test and validation sets.&#xA;&#xA;A good test set is:&#xA;&#xA;Large enough to yield statistically significant results&#xA;Representative of the dataset as a whole&#xA;Representative of real-world data the model will encounter (if your model performs poorly on real-world data, determine how your dataset differs from real-life data)&#xA;Free of duplicates from the training set&#xA;&#xA;In theory, the validation set and test set should contain the same number of examples, or nearly so.&#xA;&#xA;Source: Datasets: Dividing the original dataset | Machine Learning | Google for Developers&#xA;&#xA;Transforming data&#xA;&#xA;Machine learning models require all data, including features such as street names, to be transformed into numerical (floating-point) representations for training.&#xA;&#xA;Normalisation improves model training by converting existing floating-point features to a constrained range.&#xA;&#xA;When dealing with large datasets, select a subset of examples for training. When possible, select the subset that is most relevant to your model&#39;s predictions. Safeguard privacy by omitting examples containing personally identifiable information.&#xA;&#xA;Source: Datasets: Transforming data | Machine Learning | Google for Developers&#xA;&#xA;Generalization&#xA;&#xA;Generalisation refers to a model&#39;s ability to perform well on new, unseen data.&#xA;&#xA;Source: Generalization | Machine Learning | Google for Developers&#xA;&#xA;Overfitting&#xA;&#xA;Overfitting means creating a model that matches the training set so closely that the model fails to make correct predictions on new data.&#xA;&#xA;Generalization is the opposite of overfitting. That is, a model that generalises well makes good predictions on new data.&#xA;&#xA;An overfit model is analogous to an invention that performs well in the lab but is worthless in the real world. An underfit model is like a product that does not even do well in the lab.&#xA;&#xA;Overfitting can be detected by observing diverging loss curves for training and validation sets on a generalization curve (a graph that shows two or more loss curves). A generalization curve for a well-fit model shows two loss curves that have similar shapes.&#xA;&#xA;Common causes of overfitting include:&#xA;&#xA;A training set that does not adequately represent real-life data (or the validation set or test set).&#xA;A model that is too complex.&#xA;&#xA;Dataset conditions for good generalization include:&#xA;&#xA;Examples must be independently and identically distributed, which is a fancy way of saying that your examples cannot influence each other.&#xA;The dataset is stationary, meaning it does not change significantly over time.&#xA;The dataset partitions have the same distribution, meaning the examples in the training set, validation set, test set, and real-world data are statistically similar.&#xA;&#xA;Source: Overfitting | Machine Learning | Google for Developers&#xA;&#xA;Model complexity&#xA;&#xA;Simpler models often generalise better to new data than complex models, even if they perform slightly worse on training data.&#xA;&#xA;Occam&#39;s Razor favours simpler explanations and models.&#xA;&#xA;Model training should minimise both loss and complexity for optimal performance on new data.&#xA;$$&#xA;\text{minimise}(\text{loss + complexity})&#xA;$$&#xA;&#xA;Unfortunately, loss and complexity are typically inversely related. As complexity increases, loss decreases. As complexity decreases, loss increases.&#xA;&#xA;Regularisation techniques help prevent overfitting by penalising model complexity during training.&#xA;&#xA;L1 regularisation (also called LASSO) uses model weights to measure model complexity.&#xA;L2 regularisation (also called ridge regularisation) uses squares of model weights to measure model complexity.&#xA;&#xA;Source: Overfitting: Model complexity | Machine Learning | Google for Developers&#xA;&#xA;L2 regularization&#xA;&#xA;L2 regularisation is a popular regularisation metric to reduce model complexity and prevent overfitting. It uses the following formula:&#xA;$$&#xA;L\2 \text{ regularisation} = w^2\1 + w^2\2 + \ldots + w^2\n&#xA;$$&#xA;&#xA;It penalises especially large weights.&#xA;&#xA;L2 regularisation encourages weights towards 0, but never pushes them all the way to zero.&#xA;&#xA;A regularisation rate (lambda) controls the strength of regularisation.&#xA;$$&#xA;\text{minimise}(\text{loss} + \lambda \text{ complexity})&#xA;$$&#xA;&#xA;A high regularisation rate reduces the likelihood of overfitting and tends to produce a histogram of model weights that are normally distributed around 0.&#xA;A low regularisation rate lowers the influence of regularisation and tends to produce a histogram of model weights with a flat distribution.&#xA;&#xA;Tuning is required to find the ideal regularisation rate.&#xA;&#xA;Early stopping is an alternative regularisation method that involves ending training before the model fully converges to prevent overfitting. It usually increases training loss but decreases test loss. It is a quick but rarely optimal form of regularisation.&#xA;&#xA;Learning rate and regularisation rate tend to pull weights in opposite directions. A high learning rate often pulls weights away from zero, while a high regularisation rate pulls weights towards zero. The goal is to find the equilibrium.&#xA;&#xA;Source: Overfitting: L2 regularization | Machine Learning | Google for Developers&#xA;&#xA;Interpreting loss curves&#xA;&#xA;An ideal loss curve looks like this:&#xA;metric-curve-ideal.png&#xA;&#xA;To improve an oscillating loss curve:&#xA;&#xA;Reduce the learning rate.&#xA;Reduce the training set to a tiny number of trustworthy examples.&#xA;Check your data against a data schema to detect bad examples, then remove the bad examples from the training set.&#xA;metric-curve-ex03.png&#xA;&#xA;Possible reasons for a loss curve with a sharp jump include:&#xA;&#xA;The input data contains a burst of outliers.&#xA;The input data contains one or more NaNs (for example, a value caused by a division by zero).&#xA;metric-curve-ex02.png&#xA;&#xA;Test loss diverges from training loss when:&#xA;&#xA;The model overfits the training set.&#xA;metric-curve-ex01.png&#xA;&#xA;The loss curve gets stuck when:&#xA;&#xA;The training set is not shuffled well.&#xA;metric-curve-ex05.png&#xA;&#xA;Source: Overfitting: Interpreting loss curves | Machine Learning | Google for Developers]]&gt;</description>
      <content:encoded><![CDATA[<p>This post is part of a four-part summary of Google&#39;s <a href="https://developers.google.com/machine-learning/crash-course/">Machine Learning Crash Course</a>. For context, check out <a href="notes-from-googles-machine-learning-crash-course">this post</a>. This second module covers fundamental techniques and best practices for working with machine learning data.</p>

<h2 id="working-with-numerical-data" id="working-with-numerical-data">Working with numerical data</h2>

<h3 id="introduction" id="introduction">Introduction</h3>

<p><strong>Numerical data</strong>: Integers or floating-point values that behave like numbers. They are additive, countable, ordered, and so on. Examples include temperature, weight, or the number of deer wintering in a nature preserve.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/numerical-data">Working with numerical data | Machine Learning | Google for Developers</a></p>

<h3 id="how-a-model-ingests-data-with-feature-vectors" id="how-a-model-ingests-data-with-feature-vectors">How a model ingests data with feature vectors</h3>

<p>A machine learning model ingests data through floating-point arrays called <strong>feature vectors</strong>, which are derived from dataset features. Feature vectors often utilise processed or transformed values instead of raw dataset values to enhance model learning.</p>

<p>Example of a feature vector: [0.13, 0.47]</p>

<p>Feature engineering is the process of converting raw data into suitable representations for the model. Common techniques are:</p>
<ul><li><strong>Normalization</strong>: Converting numerical values into a standard range.</li>
<li><strong>Binning</strong> (<strong>bucketing</strong>): Converting numerical values into buckets or ranges.</li></ul>

<p>Non-numerical data like strings must be converted into numerical values for use in feature vectors.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/numerical-data/feature-vectors">Numerical data: How a model ingests data using feature vectors | Machine Learning | Google for Developers</a></p>

<h3 id="first-steps" id="first-steps">First steps</h3>

<p>Before creating feature vectors, it is crucial to analyse numerical data to detect anomalies and patterns in the data, which aids in identifying potential issues early in the data analysis process.</p>
<ul><li><strong>Visualising</strong> it through plots and graphs (like scatter plots or histograms)</li>
<li>Calculating <strong>basic statistics</strong> like mean, median, standard deviation, or values at the quartile divisions (0th, 25th, 50th, 75th, 100th percentiles, where the 50th percentile is the median)</li></ul>

<p><strong>Outliers</strong>, values significantly distant from others, should be identified and handled appropriately.</p>
<ul><li>The outlier is due to a mistake: For example, an experimenter incorrectly entered data, or an instrument malfunctioned. We generally delete examples containing mistake outliers.</li>
<li>If the outlier is a legitimate data point: If the model needs to infer good predictions on these outliers, keep them. If not, delete them or apply more invasive feature engineering techniques, such as <strong>clipping</strong>.</li></ul>

<p>A dataset probably contains outliers when:</p>
<ul><li>The delta between the 0th and 25th percentiles differs significantly from the delta between the 75th and 100th percentiles</li>
<li>The standard deviation is almost as high as the mean</li></ul>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/numerical-data/first-steps">Numerical data: First steps | Machine Learning | Google for Developers</a></p>

<h3 id="normalization" id="normalization">Normalization</h3>

<p>Data normalization is crucial for enhancing machine learning model performance by scaling features to a <strong>similar range</strong>. It is also recommended to normalise a single numeric feature that covers a wide range (for example, city population).</p>

<p>Normalisation has the following benefits:</p>
<ul><li>Helps a model converge more quickly.</li>
<li>Helps models infer better predictions.</li>
<li>Helps avoid the NaN trap (large numerical values exceeding the floating-point precision limit and flipping into NaN values).</li>
<li>Helps the model learn appropriate weights (so the model does not pay too much attention to features with wide ranges).</li></ul>

<table>
<thead>
<tr>
<th>Normalization technique</th>
<th>Formula</th>
<th>When to use</th>
</tr>
</thead>

<tbody>
<tr>
<td>Linear scaling</td>
<td>$$x&#39;=\frac{x-x_\text{min}}{x_\text{max}-x_\text{min}}$$</td>
<td>When the feature is mostly uniformly distributed across range; flat-shaped</td>
</tr>

<tr>
<td>Z-score scaling</td>
<td>$$x&#39; = (x-\mu)/\sigma$$</td>
<td>When the feature is normally distributed (peak close to mean); bell-shaped</td>
</tr>

<tr>
<td>Log scaling</td>
<td>$$x&#39;=ln(x)$$</td>
<td>When the feature distribution is heavy skewed on at least either side of tail; heavy Tail-shaped</td>
</tr>

<tr>
<td>Clipping</td>
<td>If x &gt; max, set $$x&#39;=max$$ If x &lt; min, set $$x&#39; = min$$</td>
<td>When the feature contains extreme outliers</td>
</tr>
</tbody>
</table>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/numerical-data/normalization">Numerical data: Normalization | Machine Learning | Google for Developers</a></p>

<h3 id="binning" id="binning">Binning</h3>

<p>Binning (bucketing) is a feature engineering technique used to group numerical data into categories (bins). In many cases, this turns numerical data into categorical data.</p>

<p>For example, if a feature X has values ranging from 15 to 425, we can apply binning to represent X as a feature vector divided into specific intervals:</p>

<table>
<thead>
<tr>
<th>Bin number</th>
<th>Range</th>
<th>Feature vector</th>
</tr>
</thead>

<tbody>
<tr>
<td>1</td>
<td>15-34</td>
<td>[1.0, 0.0, 0.0, 0.0, 0.0]</td>
</tr>

<tr>
<td>2</td>
<td>35-117</td>
<td>[0.0, 1.0, 0.0, 0.0, 0.0]</td>
</tr>

<tr>
<td>3</td>
<td>118-279</td>
<td>[0.0, 0.0, 1.0, 0.0, 0.0]</td>
</tr>

<tr>
<td>4</td>
<td>280-392</td>
<td>[0.0, 0.0, 0.0, 1.0, 0.0]</td>
</tr>

<tr>
<td>5</td>
<td>393-425</td>
<td>[0.0, 0.0, 0.0, 0.0, 1.0]</td>
</tr>
</tbody>
</table>

<p>Even though X is a single column in the dataset, binning causes a model to treat X as five separate features. Therefore, the model learns separate weights for each bin.</p>

<p>Binning offers an alternative to scaling or clipping and is particularly useful for handling outliers and improving model performance on non-linear data.</p>

<p><strong>When to use</strong>: Binning works well when features exhibit a “clumpy” distribution, that is, the overall <em>linear</em> relationship between the feature and label is weak or nonexistent, or when feature values are clustered.</p>

<p>Example: Number of shoppers versus temperature. By binning them, the model learns separate weights for each bin.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/binning_temperature_vs_shoppers_divided_into_3_bins.png" alt="binning_temperature_vs_shoppers_divided_into_3_bins.png"/></p>

<p>While creating multiple bins is possible, it is generally recommended to avoid an excessive number, as this can lead to insufficient training examples per bin and increased feature dimensionality.</p>

<p><strong>Quantile bucketing</strong> is a specific binning technique that ensures each bin contains a roughly equal number of examples, which can be particularly useful for datasets with skewed distributions.</p>
<ul><li>Quantile buckets give extra information space to the large torso while compacting the long tail into a single bucket.</li>
<li>Equal intervals give extra information space to the long tail while compacting the large torso into a single bucket.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/QuantileBucketing.png" alt="QuantileBucketing.png"/></li></ul>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/numerical-data/binning">Numerical data: Binning | Machine Learning | Google for Developers</a></p>

<h3 id="scrubbing" id="scrubbing">Scrubbing</h3>

<table>
<thead>
<tr>
<th>Problem category</th>
<th>Example</th>
</tr>
</thead>

<tbody>
<tr>
<td>Omitted values</td>
<td>A census taker fails to record a resident&#39;s age</td>
</tr>

<tr>
<td>Duplicate examples</td>
<td>A server uploads the same logs twice</td>
</tr>

<tr>
<td>Out-of-range feature values</td>
<td>A human accidentally types an extra digit</td>
</tr>

<tr>
<td>Bad labels</td>
<td>A human evaluator mislabels a picture of an oak tree as a maple</td>
</tr>
</tbody>
</table>

<p>You can use programs or scripts to identify and handle data issues such as omitted values, duplicates, and out-of-range feature values by removing or correcting them.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/numerical-data/scrubbing">Numerical data: Scrubbing | Machine Learning | Google for Developers</a></p>

<h3 id="qualities-of-good-numerical-features" id="qualities-of-good-numerical-features">Qualities of good numerical features</h3>
<ul><li>Good feature vectors require features that are clearly named and have obvious meanings to anyone on the project.</li>
<li>Data should be checked and tested for bad data or outliers, such as inappropriate values, before being used for training.</li>
<li>Features should be sensible, avoiding “magic values” that create discontinuities (for example, setting the value “watch_time_in_seconds” to -1 to indicate an absence of measurement); instead, use separate boolean features or new discrete values to indicate missing data.</li></ul>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/numerical-data/qualities-of-good-numerical-features">Numerical data: Qualities of good numerical features | Machine Learning | Google for Developers</a></p>

<h3 id="polynomial-transformations" id="polynomial-transformations">Polynomial transformations</h3>

<p>Synthetic features, such as polynomial transforms, enable linear models to represent non-linear relationships by introducing new features based on existing ones.</p>

<p>By incorporating synthetic features, linear regression models can effectively <strong>separate data points</strong> that are not linearly separable, using curves instead of straight lines. For example, we can separate two classes with y = x^2.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/ft_cross1.png" alt="ft_cross1.png"/></p>

<p><strong>Feature crosses</strong>, a related concept for categorical data, synthesise new features by combining existing features, further enhancing model flexibility.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/numerical-data/polynomial-transforms">Numerical data: Polynomial transforms | Machine Learning | Google for Developers</a></p>

<h2 id="working-with-categorical-data" id="working-with-categorical-data">Working with categorical data</h2>

<h3 id="introduction-1" id="introduction-1">Introduction</h3>

<p><strong>Categorical data</strong> has a specific set of possible values. Examples include species of animals, names of streets, whether or not an email is spam, and binned numbers.</p>

<p>Categorical data can include <strong>numbers that behave like categories</strong>. An example is postal codes.</p>
<ul><li>Numerical data can be meaningfully multiplied.</li>
<li>Data that are native integer values should be represented as categorical data.</li></ul>

<p><strong>Encoding</strong> means converting categorical or other data to numerical vectors that a model can train on.</p>

<p><strong>Preprocessing</strong> includes converting non-numerical data, such as strings, to floating-point values.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/categorical-data">Working with categorical data | Machine Learning | Google for Developers</a></p>

<h3 id="vocabulary-and-one-hot-encoding" id="vocabulary-and-one-hot-encoding">Vocabulary and one-hot encoding</h3>

<p>Machine learning models require numerical input; therefore, categorical data such as strings must be converted to numerical representations.</p>

<p>The term <strong>dimension</strong> is a synonym for the <strong>number of elements</strong> in a feature vector. Some categorical features are low dimensional. For example:</p>

<table>
<thead>
<tr>
<th>Feature name</th>
<th># of categories</th>
<th>Sample categories</th>
</tr>
</thead>

<tbody>
<tr>
<td>snowed_today</td>
<td>2</td>
<td>True, False</td>
</tr>

<tr>
<td>skill_level</td>
<td>3</td>
<td>Beginner, Practitioner, Expert</td>
</tr>

<tr>
<td>season</td>
<td>4</td>
<td>Winter, Spring, Summer, Autumn</td>
</tr>

<tr>
<td>day<em>of</em>week</td>
<td>7</td>
<td>Monday, Tuesday, Wednesday</td>
</tr>

<tr>
<td>planet</td>
<td>8</td>
<td>Mercury, Venus, Earth</td>
</tr>

<tr>
<td>car_colour</td>
<td>8</td>
<td>Red, Orange, Blue, Yellow</td>
</tr>
</tbody>
</table>

<p>When a categorical feature has a low number of possible categories, you can encode it as a <strong>vocabulary</strong>. This treats each category as a separate feature, allowing the model to learn distinct weights for each during training.</p>

<p><strong>One-hot encoding</strong> transforms categorical values into numerical vectors (arrays) of N elements, where N is the number of categories. Exactly one of the elements in a one-hot vector has the value 1.0; all the remaining elements have the value 0.0.</p>

<table>
<thead>
<tr>
<th>Feature</th>
<th>Red</th>
<th>Orange</th>
<th>Blue</th>
<th>Yellow</th>
<th>Green</th>
<th>Black</th>
<th>Purple</th>
<th>Brown</th>
</tr>
</thead>

<tbody>
<tr>
<td>“Red”</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>

<tr>
<td>“Orange”</td>
<td>0</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>

<tr>
<td>“Blue”</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>

<tr>
<td>“Yellow”</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>

<tr>
<td>“Green”</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>

<tr>
<td>“Black”</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>0</td>
<td>0</td>
</tr>

<tr>
<td>“Purple”</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>0</td>
</tr>

<tr>
<td>“Brown”</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
</tbody>
</table>

<p>It is the one-hot vector, not the string or the index number, that gets passed to the feature vector. The <strong>model learns a separate weight for each element</strong> of the feature vector.</p>

<p>The end-to-end process to map categories to feature vectors:
<img src="https://media.portblue.net/resources/251229_ml-crash-course/vocabulary-index-sparse-feature.png" alt="vocabulary-index-sparse-feature.png"/></p>

<p>In a true one-hot encoding, only one element has the value 1.0. In a variant known as <strong>multi-hot encoding</strong>, multiple values can be 1.0.</p>

<p>A feature whose values are predominantly zero (or empty) is termed a <strong>sparse feature</strong>.</p>

<p><strong>Sparse representation</strong> efficiently stores one-hot encoded data by only recording the position of the &#39;1&#39; value to reduce memory usage.</p>
<ul><li>For example, the one-hot vector for “car_colour” “Blue” is: [0, 0, 1, 0, 0, 0, 0, 0].</li>
<li>Since the 1 is in position 2 (when starting the count at 0), the sparse representation is: 2.</li></ul>

<p>Notice that the sparse representation consumes far less memory. Importantly, the model must train on the one-hot vector, not the sparse representation.</p>

<p>The sparse representation of a multi-hot encoding stores the positions of all the non-zero elements. For example, the sparse representation of a car that is both “Blue” and “Black” is 2, 5.</p>

<p>Categorical features can have <strong>outliers</strong>. If “car_colour” includes rare values such as “Mauve” or “Avocado”, you can group them into one <strong>out-of-vocabulary (OOV)</strong> category. All rare colours go into this single bucket, and the model learns one weight for it.</p>

<p>For <strong>high-dimensional categorical features</strong> with many categories, one-hot encoding might be inefficient, and <strong>embeddings</strong> or <strong>hashing</strong> (also called the <strong>hashing trick</strong>) are recommended.</p>
<ul><li>For example, a feature like “words_in_english” has around 500,000 categories.</li>
<li>Embeddings substantially reduce the number of dimensions, which helps the model train faster and infer predictions more quickly.</li></ul>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/categorical-data/one-hot-encoding">Categorical data: Vocabulary and one-hot encoding | Machine Learning | Google for Developers</a></p>

<h3 id="common-issues-with-categorical-data" id="common-issues-with-categorical-data">Common issues with categorical data</h3>

<p>Categorical data quality hinges on how categories are defined and labelled, impacting data reliability.</p>

<p><strong>Human-labelled data</strong>, known as “gold labels”, is generally preferred for training due to its higher quality, but it is essential to check for human errors and biases.</p>
<ul><li>Any two human beings may label the same example differently. The difference between human raters&#39; decisions is called <strong>inter-rater agreement</strong>.</li>
<li>Inter-rater agreement can be measured using kappa and intra-class correlation (<a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3402032/">Hallgren, 2012</a>), or Krippendorff&#39;s alpha (<a href="https://www.asc.upenn.edu/sites/default/files/2021-03/Computing%20Krippendorff%27s%20Alpha-Reliability.pdf">Krippendorff, 2011</a>).</li></ul>

<p><strong>Machine-labelled data</strong>, or “silver labels”, can introduce biases or inaccuracies, necessitating careful quality checks and awareness of potential common-sense violations.</p>
<ul><li>For example, if a computer-vision model mislabels a photo of a chihuahua as a muffin, or a photo of a muffin as a chihuahua.</li>
<li>Similarly, a sentiment analyser that scores neutral words as -0.25, when 0.0 is the neutral value, might be scoring all words with an additional negative bias.</li></ul>

<p><strong>High dimensionality</strong> in categorical data increases training complexity and costs, leading to techniques such as embeddings for dimensionality reduction.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/categorical-data/issues">Categorical data: Common issues | Machine Learning | Google for Developers</a></p>

<h3 id="feature-crosses" id="feature-crosses">Feature crosses</h3>

<p><strong>Feature crosses</strong> are created by combining two or more categorical or bucketed features to capture interactions and non-linearities within a dataset.</p>

<p>For example, consider a leaf dataset with the categorical features:</p>
<ul><li>“edges”, containing values {smooth, toothed, lobed}</li>
<li>“arrangement”, containing values {opposite, alternate}</li></ul>

<p>The feature cross, or Cartesian product, of these two features would be:</p>

<p>{Smooth_Opposite, Smooth_Alternate, Toothed_Opposite, Toothed_Alternate, Lobed_Opposite, Lobed_Alternate}</p>

<p>For example, if a leaf has a lobed edge and an alternate arrangement, the feature-cross vector will have a value of 1 for “Lobed_Alternate”, and a value of 0 for all other terms:</p>

<p>{0, 0, 0, 0, 0, 1}</p>

<p>This dataset could be used to classify leaves by tree species, since these characteristics do not vary within a species.</p>

<p>Feature crosses are somewhat analogous to polynomial transforms.</p>

<p>Feature crosses can be particularly effective when guided by <strong>domain expertise</strong>. It is often possible, though computationally expensive, to use neural networks to automatically find and apply useful feature combinations during training.</p>

<p>Overuse of feature crosses with sparse features should be avoided, as it can lead to <strong>excessive sparsity</strong> in the resulting feature set. For example, if feature A is a 100-element sparse feature and feature B is a 200-element sparse feature, a feature cross of A and B yields a 20,000-element sparse feature.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/categorical-data/feature-crosses">Categorical data: Feature crosses | Machine Learning | Google for Developers</a></p>

<h2 id="datasets-generalization-and-overfitting" id="datasets-generalization-and-overfitting">Datasets, generalization, and overfitting</h2>

<h3 id="introduction-2" id="introduction-2">Introduction</h3>
<ul><li>Data quality significantly impacts model performance more than algorithm choice.</li>
<li>Machine learning practitioners typically dedicate a substantial portion of their project time (around 80%) to data preparation and transformation, including tasks such as dataset construction and feature engineering.</li></ul>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/overfitting">Datasets, generalization, and overfitting | Machine Learning | Google for Developers</a></p>

<h3 id="data-characteristics" id="data-characteristics">Data characteristics</h3>

<p>A machine learning model&#39;s performance is heavily reliant on the quality and quantity of the dataset it is trained on, with <strong>larger, high-quality</strong> datasets generally leading to better results.</p>

<p>Datasets can contain various <strong>data types</strong>, including numerical, categorical, text, multimedia, and embedding vectors, each requiring specific handling for optimal model training.</p>

<p>The following are <strong>common causes</strong> of unreliable data in datasets:</p>
<ul><li>Omitted values</li>
<li>Duplicate examples</li>
<li>Bad feature values</li>
<li>Bad labels</li>
<li>Bad sections of data</li></ul>

<p>Maintaining data quality involves addressing issues such as label errors, noisy features, and proper filtering to ensure the reliability of the dataset for accurate predictions.</p>

<p>Incomplete examples with missing feature values should be handled by either <strong>deletion</strong> or <strong>imputation</strong> to avoid negatively impacting model training.</p>

<p>When imputing missing values, use reliable methods such as <strong>mean/median imputation</strong> and consider adding an indicator column to signal imputed values to the model. For example, alongside temperature include “temperature_is_imputed”. This lets the model learn to trust real observations more than imputed ones.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/overfitting/data-characteristics">Datasets: Data characteristics | Machine Learning | Google for Developers</a></p>

<h3 id="labels" id="labels">Labels</h3>

<p>Direct labels are generally preferred but often unavailable.</p>
<ul><li><strong>Direct labels</strong> exactly match the prediction target and appear explicitly in the dataset, such as a “bicycle_owner” column for predicting bicycle ownership.</li>
<li><strong>Proxy labels</strong> approximate the target and correlate with it, such as a bicycle magazine subscription as a signal of bicycle ownership.</li></ul>

<p>Use a proxy label when no direct label exists or when the direct concept resists easy numeric representation. Carefully evaluate proxy labels to ensure they are a suitable approximation.</p>

<p><strong>Human-generated labels</strong>, while offering flexibility and nuanced understanding, can be expensive to produce and prone to errors, requiring careful quality control.</p>

<p>Models can train on a mix of <strong>automated</strong> and human-generated labels, but an extra set of human labels often adds complexity without sufficient benefit.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/overfitting/labels">Datasets: Labels | Machine Learning | Google for Developers</a></p>

<h3 id="imbalanced-datasets" id="imbalanced-datasets">Imbalanced datasets</h3>

<p><strong>Imbalanced datasets</strong> occur when one label (<strong>majority class</strong>) is significantly more frequent than another (<strong>minority class</strong>), potentially hindering model training on the minority class.</p>

<p>Note: Accuracy is usually a poor metric for assessing a model trained on a class-imbalanced dataset.</p>

<p>A highly imbalanced floral dataset containing far more sunflowers (200) than roses (2):
<img src="https://media.portblue.net/resources/251229_ml-crash-course/FloralDataset200Sunflowers2Roses.png" alt="FloralDataset200Sunflowers2Roses.png"/></p>

<p>During training, a model should learn two things:</p>
<ul><li>What each class looks like, that is, what feature values correspond to which class.</li>
<li>How common each class is, that is, what the relative distribution of the classes is.</li></ul>

<p>Standard training conflates these two goals. In contrast, a two-step technique of <strong>downsampling and upweighting the majority class</strong> separates these two goals, enabling the model to achieve both.</p>

<p><strong>Step 1: Downsample the majority class</strong> by training on only a small fraction of majority class examples, which makes an imbalanced dataset more balanced during training and increases the chance that each batch contains enough minority examples.</p>

<p>For example, with a class-imbalanced dataset consisting of 99% majority class and 1% minority class examples, we could downsample the majority class by a factor of 25 to create a more balanced training set (80% majority class and 20% minority class).</p>

<p>Downsampling the majority class by a factor of 25:
<img src="https://media.portblue.net/resources/251229_ml-crash-course/FloralDatasetDownsampling.png" alt="FloralDatasetDownsampling.png"/></p>

<p><strong>Step 2: Upweight the downsampled majority class</strong> by the same factor used for downsampling, so each majority class error counts proportionally more during training. This corrects the artificial class distribution and bias introduced by downsampling, because the training data no longer reflects real-world frequencies.</p>

<p>Continuing the example from above, we must upweight the majority class by a factor of 25. That is, when the model mistakenly predicts the majority class, treat the loss as if it were 25 errors (multiply the regular loss by 25).</p>

<p>Upweighting the majority class by a factor of 25:
<img src="https://media.portblue.net/resources/251229_ml-crash-course/FloralDatasetUpweighting.png" alt="FloralDatasetUpweighting.png"/></p>

<p>Experiment with different <strong>downsampling and upweighting factors</strong> just as you would experiment with other hyperparameters.</p>

<p><strong>Benefits of this technique</strong> include a better model (the resultant model knows what each class looks like and how common each class is) and faster convergence.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/overfitting/imbalanced-datasets">Datasets: Class-imbalanced datasets | Machine Learning | Google for Developers</a></p>

<h3 id="dividing-the-original-dataset" id="dividing-the-original-dataset">Dividing the original dataset</h3>

<p>Machine learning models should be tested against unseen data.</p>

<p>It is recommended to split the dataset into three subsets: training, validation, and test sets.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/PartitionThreeSets.png" alt="PartitionThreeSets.png"/></p>

<p>The validation set is used for initial testing during training (to determine hyperparameter tweaks, add, remove, or transform features, and so on), and the test set is used for final evaluation.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/workflow_with_validation_set.png" alt="workflow_with_validation_set.png"/></p>

<p>The validation and test sets can “wear out” with repeated use. For this reason, it is a good idea to collect more data to “refresh” the test and validation sets.</p>

<p>A <strong>good test set</strong> is:</p>
<ul><li>Large enough to yield statistically significant results</li>
<li>Representative of the dataset as a whole</li>
<li>Representative of real-world data the model will encounter (if your model performs poorly on real-world data, determine how your dataset differs from real-life data)</li>
<li>Free of duplicates from the training set</li></ul>

<p>In theory, the validation set and test set should contain the same number of examples, or nearly so.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/overfitting/dividing-datasets">Datasets: Dividing the original dataset | Machine Learning | Google for Developers</a></p>

<h3 id="transforming-data" id="transforming-data">Transforming data</h3>

<p>Machine learning models require all data, including features such as street names, to be transformed into <strong>numerical (floating-point) representations</strong> for training.</p>

<p><strong>Normalisation</strong> improves model training by converting existing floating-point features to a constrained range.</p>

<p>When dealing with large datasets, select a subset of examples for training. When possible, select the subset that is most relevant to your model&#39;s predictions. Safeguard privacy by omitting examples containing personally identifiable information.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/overfitting/transforming-data">Datasets: Transforming data | Machine Learning | Google for Developers</a></p>

<h3 id="generalization" id="generalization">Generalization</h3>

<p>Generalisation refers to a model&#39;s ability to perform well on new, unseen data.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/overfitting/generalization">Generalization | Machine Learning | Google for Developers</a></p>

<h3 id="overfitting" id="overfitting">Overfitting</h3>

<p><strong>Overfitting</strong> means creating a model that matches the training set so closely that the model fails to make correct predictions on new data.</p>

<p><strong>Generalization</strong> is the opposite of overfitting. That is, a model that generalises well makes good predictions on new data.</p>

<p>An overfit model is analogous to an invention that performs well in the lab but is worthless in the real world. An underfit model is like a product that does not even do well in the lab.</p>

<p>Overfitting can be <strong>detected</strong> by observing diverging loss curves for training and validation sets on a generalization curve (a graph that shows two or more loss curves). A generalization curve for a well-fit model shows two loss curves that have similar shapes.</p>

<p><strong>Common causes</strong> of overfitting include:</p>
<ul><li>A training set that does not adequately represent real-life data (or the validation set or test set).</li>
<li>A model that is too complex.</li></ul>

<p>Dataset conditions for good generalization include:</p>
<ul><li>Examples must be <strong>independently and identically distributed</strong>, which is a fancy way of saying that your examples cannot influence each other.</li>
<li>The dataset is <strong>stationary</strong>, meaning it does not change significantly over time.</li>
<li>The dataset partitions have the <strong>same distribution</strong>, meaning the examples in the training set, validation set, test set, and real-world data are statistically similar.</li></ul>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/overfitting/overfitting">Overfitting | Machine Learning | Google for Developers</a></p>

<h3 id="model-complexity" id="model-complexity">Model complexity</h3>

<p><strong>Simpler models often generalise better</strong> to new data than complex models, even if they perform slightly worse on training data.</p>

<p><strong>Occam&#39;s Razor</strong> favours simpler explanations and models.</p>

<p>Model training should minimise both loss and complexity for optimal performance on new data.
$$
\text{minimise}(\text{loss + complexity})
$$</p>

<p>Unfortunately, loss and complexity are typically inversely related. As complexity increases, loss decreases. As complexity decreases, loss increases.</p>

<p><strong>Regularisation techniques</strong> help prevent overfitting by penalising model complexity during training.</p>
<ul><li><strong>L1 regularisation</strong> (also called LASSO) uses model weights to measure model complexity.</li>
<li><strong>L2 regularisation</strong> (also called ridge regularisation) uses squares of model weights to measure model complexity.</li></ul>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/overfitting/model-complexity">Overfitting: Model complexity | Machine Learning | Google for Developers</a></p>

<h3 id="l2-regularization" id="l2-regularization">L2 regularization</h3>

<p><strong>L2 regularisation</strong> is a popular regularisation metric to reduce model complexity and prevent overfitting. It uses the following formula:
$$
L_2 \text{ regularisation} = w^2_1 + w^2_2 + \ldots + w^2_n
$$</p>

<p>It penalises especially large weights.</p>

<p>L2 regularisation encourages weights towards 0, but never pushes them all the way to zero.</p>

<p>A <strong>regularisation rate (lambda)</strong> controls the strength of regularisation.
$$
\text{minimise}(\text{loss} + \lambda \text{ complexity})
$$</p>
<ul><li>A <strong>high regularisation rate</strong> reduces the likelihood of overfitting and tends to produce a histogram of model weights that are normally distributed around 0.</li>
<li>A <strong>low regularisation rate</strong> lowers the influence of regularisation and tends to produce a histogram of model weights with a flat distribution.</li></ul>

<p>Tuning is required to find the ideal regularisation rate.</p>

<p><strong>Early stopping</strong> is an alternative regularisation method that involves ending training before the model fully converges to prevent overfitting. It usually increases training loss but decreases test loss. It is a quick but rarely optimal form of regularisation.</p>

<p><strong>Learning rate</strong> and <strong>regularisation rate</strong> tend to pull weights in opposite directions. A high learning rate often pulls weights away from zero, while a high regularisation rate pulls weights towards zero. The goal is to find the equilibrium.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/overfitting/regularization">Overfitting: L2 regularization | Machine Learning | Google for Developers</a></p>

<h3 id="interpreting-loss-curves" id="interpreting-loss-curves">Interpreting loss curves</h3>

<p>An <strong>ideal loss curve</strong> looks like this:
<img src="https://media.portblue.net/resources/251229_ml-crash-course/metric-curve-ideal.png" alt="metric-curve-ideal.png"/></p>

<p>To improve an <strong>oscillating loss curve</strong>:</p>
<ul><li>Reduce the learning rate.</li>
<li>Reduce the training set to a tiny number of trustworthy examples.</li>
<li>Check your data against a data schema to detect bad examples, then remove the bad examples from the training set.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/metric-curve-ex03.png" alt="metric-curve-ex03.png"/></li></ul>

<p>Possible reasons for a <strong>loss curve with a sharp jump</strong> include:</p>
<ul><li>The input data contains a burst of outliers.</li>
<li>The input data contains one or more NaNs (for example, a value caused by a division by zero).
<img src="https://media.portblue.net/resources/251229_ml-crash-course/metric-curve-ex02.png" alt="metric-curve-ex02.png"/></li></ul>

<p><strong>Test loss diverges from training loss</strong> when:</p>
<ul><li>The model overfits the training set.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/metric-curve-ex01.png" alt="metric-curve-ex01.png"/></li></ul>

<p>The <strong>loss curve gets stuck</strong> when:</p>
<ul><li>The training set is not shuffled well.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/metric-curve-ex05.png" alt="metric-curve-ex05.png"/></li></ul>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/overfitting/interpreting-loss-curves">Overfitting: Interpreting loss curves | Machine Learning | Google for Developers</a></p>
]]></content:encoded>
      <guid>https://stefan.angrick.me/google-ml-crash-course-2-notes-data</guid>
      <pubDate>Mon, 29 Dec 2025 10:02:48 +0000</pubDate>
    </item>
    <item>
      <title>Google ML Crash Course #1 Notes: ML Models</title>
      <link>https://stefan.angrick.me/google-ml-crash-course-1-notes-ml-models?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[This post is part of a four-part summary of Google&#39;s Machine Learning Crash Course. For context, check out this post. This first module covers the fundamentals of building regression and classification models.!--more--&#xA;&#xA;Linear regression&#xA;&#xA;Introduction&#xA;&#xA;The linear regression model uses an equation&#xA;$$&#xA;y&#39; = b + w\1x\1 + w\2x\2 + \ldots&#xA;$$&#xA;to represent the relationship between features and the label.&#xA;&#xA;y&#39; is the predicted label--the output&#xA;b is the bias of the model (the y-intercept in algebraic terms), sometimes referred to as w\0&#xA;w\1 is the weight of the feature (the slope in algebraic terms)&#xA;x\1 is a feature--the input&#xA;&#xA;y and features x are given. b and w are calculated from training by minimizing the difference between predicted and actual values.&#xA;&#xA;Source: Linear regression | Machine Learning | Google for Developers&#xA;&#xA;Loss&#xA;&#xA;Loss is a numerical value indicating the difference between a model&#39;s predictions and the actual values.&#xA;&#xA;The goal of model training is to minimize loss, bringing it as close to zero as possible.&#xA;&#xA;| Loss type                     | Definition                                                                                            | Equation                                                         |&#xA;| ----------------------------- | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |&#xA;| L1 loss                   | The sum of the absolute values of the difference  between the predicted values and the actual values. | $$\sum \|\text{actual value}-\text{predicted value}\|$$            |&#xA;| Mean absolute error (MAE) | The average of L1 losses across a set of N examples.                                                | $$\frac{1}{N}\sum \|\text{actual value}-\text{predicted value}\|$$ |&#xA;| L2 loss                   | The sum of the squared difference between the predicted values and the actual values.                 | $$\sum (\text{actual value}-\text{predicted value})^2$$            |&#xA;| Mean squared error (MSE)  | The average of L2 losses across a set of N examples.                                                | $$\frac{1}{N}\sum (\text{actual value}-\text{predicted value})^2$$ |&#xA;&#xA;The most common methods for calculating loss are Mean Absolute Error (MAE) and Mean Squared Error (MSE), which differ in their sensitivity to outliers.&#xA;&#xA;A model trained with MSE moves the model closer to the outliers but further away from most of the other data points.&#xA;model-mse.png&#xA;&#xA;A model trained with MAE is farther from the outliers but closer to most of the other data points.&#xA;model-mae.png&#xA;&#xA;Source: Linear regression: Loss | Machine Learning | Google for Developers&#xA;&#xA;Gradient descent&#xA;&#xA;Gradient descent is an iterative optimisation algorithm used to find the best weights and bias for a linear regression model by minimising the loss function.&#xA;&#xA;Calculate the loss with the current weight and bias.&#xA;Determine the direction to move the weights and bias that reduce loss.&#xA;Move the weight and bias values a small amount in the direction that reduces loss.&#xA;Return to step one and repeat the process until the model can&#39;t reduce the loss any further.&#xA;&#xA;A model is considered to have converged when further iterations do not significantly reduce the loss, indicating it has found the weights and bias that produce the lowest possible loss.&#xA;&#xA;Loss curves visually represent the model&#39;s progress during training, showing how the loss decreases over iterations and helping to identify convergence.&#xA;&#xA;Linear models have convex loss functions, ensuring that gradient descent will always find the global minimum, resulting in the best possible model for the given data.&#xA;&#xA;Source: Linear regression: Gradient descent | Google for Developers&#xA;&#xA;Hyperparameters&#xA;&#xA;Hyperparameters, such as learning rate, batch size, and epochs, are external configurations that influence the training process of a machine learning model.&#xA;&#xA;The learning rate determines the step size during gradient descent, impacting the speed and stability of convergence.&#xA;&#xA;If the learning rate is too low, the model can take a long time to converge.&#xA;However, if the learning rate is too high, the model never converges, but instead bounces around the weights and bias that minimise the loss.&#xA;&#xA;Batch size dictates the number of training examples processed before updating model parameters, influencing training speed and noise.&#xA;&#xA;When a dataset contains hundreds of thousands or even millions of examples, using the full batch isn&#39;t practical.&#xA;Two common techniques to get the right gradient on average without needing to look at every example in the dataset before updating the weights and bias are stochastic gradient descent and mini-batch stochastic gradient descent.&#xA;  Stochastic gradient descent uses only a single random example (a batch size of one) per iteration. Given enough iterations, SGD works but is very noisy.&#xA;  Mini-batch stochastic gradient descent is a compromise between full-batch and SGD. For N number of data points, the batch size can be any number greater than 1 and less than N. The model chooses the examples included in each batch at random, averages their gradients, and then updates the weights and bias once per iteration.&#xA;&#xA;Model trained with SGD:&#xA;noisy-gradient.png&#xA;&#xA;Model trained with mini-batch SGD:&#xA;mini-batch-sgd.png&#xA;&#xA;Epochs represent the number of times the entire training dataset is used during training, affecting model performance and training time.&#xA;&#xA;For example, given a training set with 1,000 examples and a mini-batch size of 100 examples, it will take the model 10 iterations to complete one epoch.&#xA;&#xA;Source: Linear regression: Hyperparameters | Machine Learning | Google for Developers&#xA;&#xA;Logistic regression&#xA;&#xA;Introduction&#xA;&#xA;Logistic regression is a model used to predict the probability of an outcome, unlike linear regression which predicts continuous numerical values.&#xA;&#xA;Logistic regression models output probabilities, which can be used directly or converted to binary categories.&#xA;&#xA;Source: Logistic Regression | Machine Learning | Google for Developers&#xA;&#xA;Calculating a probability with the sigmoid function&#xA;&#xA;A logistic regression model uses a linear equation and the sigmoid function to calculate the probability of an event.&#xA;&#xA;The sigmoid function ensures the output of logistic regression is always between 0 and 1, representing a probability.&#xA;$$&#xA;f(x) = \frac{1}{1 + e^{-x}}&#xA;$$&#xA;sigmoidfunctionwithaxes.png&#xA;&#xA;Linear component of a logistic regression model:&#xA;$$&#xA;z = b + w\1 x\1 + w\2 x\2 + \ldots + w\N x\N&#xA;$$&#xA;To obtain the logistic regression prediction, the z value is then passed to the sigmoid function, yielding a value (a probability) between 0 and 1:&#xA;$$&#xA;y&#39; = \frac{1}{1+e^{-z}}&#xA;$$&#xA;&#xA;y&#39; is the output of the logistic regression model.&#xA;z is the linear output (as calculated in the preceding equation).&#xA;&#xA;z is referred to as the log-odds because if you solve the sigmoid function for z you get:&#xA;$$&#xA;z = \log(\frac{y}{1-y})&#xA;$$&#xA;This is the log of the ratio of the probabilities of the two possible outcomes: y and 1 - y.&#xA;&#xA;When the linear equation becomes input to the sigmoid function, it bends the straight line into an s-shape.&#xA;lineartologistic.png&#xA;&#xA;Source: Logistic regression: Calculating a probability with the sigmoid function | Machine Learning | Google for Developers&#xA;&#xA;Loss and regularisation&#xA;&#xA;Logistic regression models are trained similarly to linear regression models but use Log Loss instead of squared loss and require regularisation.&#xA;&#xA;Log Loss is used in logistic regression because the rate of change isn&#39;t constant, requiring varying precision levels unlike squared loss used in linear regression.&#xA;&#xA;The Log Loss equation returns the logarithm of the magnitude of the change, rather than just the distance from data to prediction. Log Loss is calculated as follows:&#xA;$$&#xA;\text{Log Loss} = \sum{(x,y)\in D} -y\log(y&#39;) - (1 - y)\log(1 - y&#39;)&#xA;$$&#xA;&#xA;(x,y) is the dataset containing many labelled examples, which are (x, y) pairs.&#xA;y is the label in a labelled example. Since this is logistic regression, every value of y must either be 0 or 1.&#xA;y&#39; is your model&#39;s prediction (somewhere between 0 and 1), given the set of features in x.&#xA;&#xA;Regularisation, such as L2 regularisation or early stopping, is crucial in logistic regression to prevent overfitting (due to the model&#39;s asymptotic nature) and improve generalisation.&#xA;&#xA;Source: Logistic regression: Loss and regularization | Machine Learning | Google for Developers&#xA;&#xA;Classification&#xA;&#xA;Introduction&#xA;&#xA;Logistic regression models can be converted into binary classification models for predicting categories instead of probabilities.&#xA;&#xA;Source: Classification | Machine Learning | Google for Developers&#xA;&#xA;Thresholds and the confusion matrix&#xA;&#xA;To convert the raw output from a logistic regression model into binary classification (positive and negative class), you need a classification threshold.&#xA;&#xA;Confusion matrix&#xA;&#xA;|                        | Actual positive     | Actual negative     |&#xA;| ---------------------- | ------------------- | ------------------- |&#xA;| Predicted positive | True positive (TP)  | False positive (FP) |&#xA;| Predicted negative | False negative (FN) | True negative (TN)  |&#xA;&#xA;Total of each row = all predicted positives (TP + FP) and all predicted negatives (FN + TN)&#xA;Total of each column = all real positives (TP + FN) and all real negatives (FP + TN)&#xA;&#xA;When positive examples and negative examples are generally well differentiated, with most positive examples having higher scores than negative examples, the dataset is separated.&#xA;When the total of actual positives is not close to the total of actual negatives, the dataset is imbalanced.&#xA;When many positive examples have lower scores than negative examples, and many negative examples have higher scores than positive examples, the dataset is unseparated.&#xA;&#xA;When we increase the classification threshold, both TP and FP decrease, and both TN and FN increase.&#xA;&#xA;Source: Thresholds and the confusion matrix | Machine Learning | Google for Developers&#xA;&#xA;Accuracy, recall, precision, and related metrics&#xA;&#xA;Accuracy, Recall, Precision, and related metrics are all calculated at a single classification threshold value.&#xA;&#xA;Accuracy is the proportion of all classifications that were correct.&#xA;$$&#xA;\text{Accuracy} = \frac{\text{correct classifications}}{\text{total classifications}} = \frac{TP+TN}{TP+TN+FP+FN}&#xA;$$&#xA;&#xA;Use as a rough indicator of model training progress/convergence for balanced datasets. Typically the default.&#xA;For model performance, use only in combination with other metrics.&#xA;Avoid for imbalanced datasets. Consider using another metric.&#xA;&#xA;Recall, or true positive rate, is the proportion of all actual positives that were classified correctly as positives. Also known as probability of detection.&#xA;$$&#xA;\text{Recall (or TPR)} = \frac{\text{correctly classified actual positives}}{\text{all actual positives}} = \frac{TP}{TP+FN}&#xA;$$&#xA;&#xA;Use when false negatives are more expensive than false positives.&#xA;Better than Accuracy in imbalanced datasets.&#xA;Improves when false negatives decrease.&#xA;&#xA;False positive rate is the proportion of all actual negatives that were classified incorrectly as positives. Also known as probability of a false alarm.&#xA;$$&#xA;\text{FPR} = \frac{\text{incorrectly classified actual negatives}}{\text{all actual negatives}}=\frac{FP}{FP+TN}&#xA;$$&#xA;&#xA;Use when false positives are more expensive than false negatives.&#xA;Less meaningful and useful in a dataset where the number of actual negtives is very, very low.&#xA;&#xA;Precision is the proportion of all the model&#39;s positive classifications that are actually positive.&#xA;$$&#xA;\text{Precision} = \frac{\text{correctly classified actual positives}}{\text{everything classified as positive}}=\frac{TP}{TP+FP}&#xA;$$&#xA;&#xA;Use when it&#39;s very important for positive predictions to be accurate.&#xA;Less meaningful and useful in a dataset where the number of actual positives is very, very low.&#xA;Improves as false positives decrease.&#xA;&#xA;Precision and Recall often show an inverse relationship.&#xA;&#xA;F1 score is the harmonic mean of Precision and Recall.&#xA;$$&#xA;\text{F1} = 2  \frac{\text{precision}  \text{recall}}{\text{precision} + \text{recall}} = \frac{2TP}{2TP + FP + FN}&#xA;$$&#xA;&#xA;Preferable for class-imbalanced datasets.&#xA;When Precision and Recall are close in value, F1 will be close to their value.&#xA;When Precision and Recall are far apart, F1 will be similar to whichever metric is worse.&#xA;&#xA;Source: Classification: Accuracy, recall, precision, and related metrics | Machine Learning | Google for Developers&#xA;&#xA;ROC and AUC&#xA;&#xA;ROC and AUC evaluate a model&#39;s quality across all possible thresholds.&#xA;&#xA;ROC curve, or receiver operating characteristic curves, plot the true positive rate (TPR) against the false positive rate (FPR) at different thresholds. A perfect model would pass through (0,1), while a random guesser forms a diagonal line from (0,0) to (1,1).&#xA;&#xA;AUC, or area under the curve, represents the probability that the model will rank a randomly chosen positive example higher than a negative example. A perfect model has AUC = 1.0, while a random model has AUC = 0.5.&#xA;&#xA;ROC and AUC of a hypothetical perfect model (AUC = 1.0) and for completely random guesses (AUC = 0.5):&#xA;auc1-0.pngauc0-5.png&#xA;&#xA;ROC and AUC are effective when class distributions are balanced. For imbalanced data, precision-recall curves (PRCs) can be more informative.&#xA;prauc.png&#xA;&#xA;A higher AUC generally indicates a better-performing model.&#xA;&#xA;ROC and AUC of two hypothetical models; the first curve (AUC = 0.65) represents the better of the two models:&#xA;auc0-65.png&#xA;auc0-93.png&#xA;&#xA;Threshold choice depends on the cost of false positives versus false negatives. The most relevant thresholds are those closest to (0,1) on the ROC curve. For costly false positives, a conservative threshold (like A in the chart below) is better. For costly false negatives, a more sensitive threshold (like C) is preferable. If costs are roughly equivalent, a threshold in the middle (like B) may be best.&#xA;aucabc.png&#xA;&#xA;Source: Classification: ROC and AUC | Machine Learning | Google for Developers&#xA;&#xA;Prediction bias&#xA;&#xA;Prediction bias measures the difference between the average of a model&#39;s predictions and the average of the true labels in the data. For example, if 5% of emails in the dataset are spam, a model without prediction bias should also predict about 5% as spam. A large mismatch between these averages indicates potential problems.&#xA;&#xA;Prediction bias can be caused by:&#xA;&#xA;Biased and noisy data (e.g., skewed sampling)&#xA;Overly strong regularisation that oversimplifies the model&#xA;Bugs in the model training pipeline&#xA;Insufficient features provided to the model&#xA;&#xA;Source: Classification: Prediction bias | Machine Learning | Google for Developers&#xA;&#xA;Multi-class classification&#xA;&#xA;Multi-class classification extends binary classification to cases with more than two classes.&#xA;&#xA;If each example belongs to only one class, the problem can be broken down into a series of binary classifications. For instance, with three classes (A, B, C), you could first separate C from A+B, then distinguish A from B within the A+B group.&#xA;&#xA;Source: Classification: Multi-class classification | Machine Learning | Google for Developers]]&gt;</description>
      <content:encoded><![CDATA[<p>This post is part of a four-part summary of Google&#39;s <a href="https://developers.google.com/machine-learning/crash-course/">Machine Learning Crash Course</a>. For context, check out <a href="notes-from-googles-machine-learning-crash-course">this post</a>. This first module covers the fundamentals of building regression and classification models.</p>

<h2 id="linear-regression" id="linear-regression">Linear regression</h2>

<h3 id="introduction" id="introduction">Introduction</h3>

<p>The linear regression model uses an equation
$$
y&#39; = b + w_1x_1 + w_2x_2 + \ldots
$$
to represent the relationship between features and the label.</p>
<ul><li>y&#39; is the <strong>predicted label</strong>—the output</li>
<li>b is the <strong>bias</strong> of the model (the y-intercept in algebraic terms), sometimes referred to as w_0</li>
<li>w_1 is the <strong>weight</strong> of the feature (the slope in algebraic terms)</li>
<li>x_1 is a <strong>feature</strong>—the input</li></ul>

<p>y and features x are given. b and w are calculated from training by minimizing the difference between predicted and actual values.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/linear-regression">Linear regression | Machine Learning | Google for Developers</a></p>

<h3 id="loss" id="loss">Loss</h3>

<p>Loss is a numerical value indicating the difference between a model&#39;s predictions and the actual values.</p>

<p>The goal of model training is to minimize loss, bringing it as close to zero as possible.</p>

<table>
<thead>
<tr>
<th>Loss type</th>
<th>Definition</th>
<th>Equation</th>
</tr>
</thead>

<tbody>
<tr>
<td><strong>L1 loss</strong></td>
<td>The sum of the absolute values of the difference  between the predicted values and the actual values.</td>
<td>$$\sum |\text{actual value}-\text{predicted value}|$$</td>
</tr>

<tr>
<td><strong>Mean absolute error (MAE)</strong></td>
<td>The average of L1 losses across a set of <em>N</em> examples.</td>
<td>$$\frac{1}{N}\sum |\text{actual value}-\text{predicted value}|$$</td>
</tr>

<tr>
<td><strong>L2 loss</strong></td>
<td>The sum of the squared difference between the predicted values and the actual values.</td>
<td>$$\sum (\text{actual value}-\text{predicted value})^2$$</td>
</tr>

<tr>
<td><strong>Mean squared error (MSE)</strong></td>
<td>The average of L2 losses across a set of <em>N</em> examples.</td>
<td>$$\frac{1}{N}\sum (\text{actual value}-\text{predicted value})^2$$</td>
</tr>
</tbody>
</table>

<p>The most common methods for calculating loss are Mean Absolute Error (MAE) and Mean Squared Error (MSE), which differ in their sensitivity to outliers.</p>

<p>A model trained with <strong>MSE</strong> moves the model closer to the outliers but further away from most of the other data points.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/model-mse.png" alt="model-mse.png"/></p>

<p>A model trained with <strong>MAE</strong> is farther from the outliers but closer to most of the other data points.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/model-mae.png" alt="model-mae.png"/></p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/linear-regression/loss">Linear regression: Loss | Machine Learning | Google for Developers</a></p>

<h3 id="gradient-descent" id="gradient-descent">Gradient descent</h3>

<p><strong>Gradient descent</strong> is an iterative optimisation algorithm used to find the best weights and bias for a linear regression model by minimising the loss function.</p>
<ol><li>Calculate the loss with the current weight and bias.</li>
<li>Determine the direction to move the weights and bias that reduce loss.</li>
<li>Move the weight and bias values a small amount in the direction that reduces loss.</li>
<li>Return to step one and repeat the process until the model can&#39;t reduce the loss any further.</li></ol>

<p>A model is considered to have <strong>converged</strong> when further iterations do not significantly reduce the loss, indicating it has found the weights and bias that produce the lowest possible loss.</p>

<p><strong>Loss curves</strong> visually represent the model&#39;s progress during training, showing how the loss decreases over iterations and helping to identify convergence.</p>

<p>Linear models have <strong>convex</strong> loss functions, ensuring that gradient descent will always find the global minimum, resulting in the best possible model for the given data.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/linear-regression/gradient-descent">Linear regression: Gradient descent | Google for Developers</a></p>

<h3 id="hyperparameters" id="hyperparameters">Hyperparameters</h3>

<p>Hyperparameters, such as <strong>learning rate</strong>, <strong>batch size</strong>, and <strong>epochs</strong>, are external configurations that influence the training process of a machine learning model.</p>

<p>The <strong>learning rate</strong> determines the step size during gradient descent, impacting the <strong>speed and stability of convergence</strong>.</p>
<ul><li>If the learning rate is too low, the model can take a long time to converge.</li>
<li>However, if the learning rate is too high, the model never converges, but instead bounces around the weights and bias that minimise the loss.</li></ul>

<p><strong>Batch size</strong> dictates the number of training examples processed before updating model parameters, influencing training speed and noise.</p>
<ul><li>When a dataset contains hundreds of thousands or even millions of examples, using the full batch isn&#39;t practical.</li>
<li>Two common techniques to get the right gradient on average without needing to look at every example in the dataset before updating the weights and bias are <strong>stochastic gradient descent</strong> and <strong>mini-batch stochastic gradient descent</strong>.
<ul><li><strong>Stochastic gradient descent</strong> uses only a single random example (a batch size of one) per iteration. Given enough iterations, SGD works but is very noisy.</li>
<li><strong>Mini-batch stochastic gradient descent</strong> is a compromise between full-batch and SGD. For N number of data points, the batch size can be any number greater than 1 and less than N. The model chooses the examples included in each batch at random, averages their gradients, and then updates the weights and bias once per iteration.</li></ul></li></ul>

<p>Model trained with SGD:
<img src="https://media.portblue.net/resources/251229_ml-crash-course/noisy-gradient.png" alt="noisy-gradient.png"/></p>

<p>Model trained with mini-batch SGD:
<img src="https://media.portblue.net/resources/251229_ml-crash-course/mini-batch-sgd.png" alt="mini-batch-sgd.png"/></p>

<p><strong>Epochs</strong> represent the number of times the entire training dataset is used during training, affecting model performance and training time.</p>
<ul><li>For example, given a training set with <strong>1,000 examples</strong> and a <strong>mini-batch size of 100</strong> examples, it will take the model <strong>10 iterations</strong> to complete <strong>one epoch</strong>.</li></ul>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/linear-regression/hyperparameters">Linear regression: Hyperparameters | Machine Learning | Google for Developers</a></p>

<h2 id="logistic-regression" id="logistic-regression">Logistic regression</h2>

<h3 id="introduction-1" id="introduction-1">Introduction</h3>

<p>Logistic regression is a model used to predict the probability of an outcome, unlike linear regression which predicts continuous numerical values.</p>

<p>Logistic regression models output probabilities, which can be used directly or converted to binary categories.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/logistic-regression">Logistic Regression | Machine Learning | Google for Developers</a></p>

<h3 id="calculating-a-probability-with-the-sigmoid-function" id="calculating-a-probability-with-the-sigmoid-function">Calculating a probability with the sigmoid function</h3>

<p>A logistic regression model uses a linear equation and the sigmoid function to calculate the probability of an event.</p>

<p>The <strong>sigmoid function</strong> ensures the output of logistic regression is always between 0 and 1, representing a probability.
$$
f(x) = \frac{1}{1 + e^{-x}}
$$
<img src="https://media.portblue.net/resources/251229_ml-crash-course/sigmoid_function_with_axes.png" alt="sigmoid_function_with_axes.png"/></p>

<p>Linear component of a logistic regression model:
$$
z = b + w_1 x_1 + w_2 x_2 + \ldots + w_N x_N
$$
To obtain the logistic regression prediction, the <em>z</em> value is then passed to the sigmoid function, yielding a value (a probability) between 0 and 1:
$$
y&#39; = \frac{1}{1+e^{-z}}
$$</p>
<ul><li>y&#39; is the output of the logistic regression model.</li>
<li>z is the linear output (as calculated in the preceding equation).</li></ul>

<p>z is referred to as the <strong>log-odds</strong> because if you solve the sigmoid function for z you get:
$$
z = \log(\frac{y}{1-y})
$$
This is the log of the ratio of the probabilities of the two possible outcomes: y and 1 – y.</p>

<p>When the linear equation becomes input to the sigmoid function, it bends the straight line into an s-shape.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/linear_to_logistic.png" alt="linear_to_logistic.png"/></p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/logistic-regression/sigmoid-function">Logistic regression: Calculating a probability with the sigmoid function | Machine Learning | Google for Developers</a></p>

<h3 id="loss-and-regularisation" id="loss-and-regularisation">Loss and regularisation</h3>

<p>Logistic regression models are trained similarly to linear regression models but use Log Loss instead of squared loss and require regularisation.</p>

<p><strong>Log Loss</strong> is used in logistic regression because the rate of change isn&#39;t constant, requiring varying precision levels unlike squared loss used in linear regression.</p>

<p>The Log Loss equation returns the logarithm of the magnitude of the change, rather than just the distance from data to prediction. Log Loss is calculated as follows:
$$
\text{Log Loss} = \sum_{(x,y)\in D} -y\log(y&#39;) – (1 – y)\log(1 – y&#39;)
$$</p>
<ul><li>(x,y) is the dataset containing many labelled examples, which are (x, y) pairs.</li>
<li>y is the label in a labelled example. Since this is logistic regression, every value of y must either be 0 or 1.</li>
<li>y&#39; is your model&#39;s prediction (somewhere between 0 and 1), given the set of features in x.</li></ul>

<p><strong>Regularisation</strong>, such as L2 regularisation or early stopping, is crucial in logistic regression to prevent overfitting (due to the model&#39;s asymptotic nature) and improve generalisation.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/logistic-regression/loss-regularization">Logistic regression: Loss and regularization | Machine Learning | Google for Developers</a></p>

<h2 id="classification" id="classification">Classification</h2>

<h3 id="introduction-2" id="introduction-2">Introduction</h3>

<p>Logistic regression models can be converted into binary classification models for predicting categories instead of probabilities.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/classification">Classification | Machine Learning | Google for Developers</a></p>

<h3 id="thresholds-and-the-confusion-matrix" id="thresholds-and-the-confusion-matrix">Thresholds and the confusion matrix</h3>

<p>To convert the raw output from a logistic regression model into binary classification (positive and negative class), you need a classification threshold.</p>

<p><strong>Confusion matrix</strong></p>

<table>
<thead>
<tr>
<th></th>
<th>Actual positive</th>
<th>Actual negative</th>
</tr>
</thead>

<tbody>
<tr>
<td><strong>Predicted positive</strong></td>
<td>True positive (TP)</td>
<td>False positive (FP)</td>
</tr>

<tr>
<td><strong>Predicted negative</strong></td>
<td>False negative (FN)</td>
<td>True negative (TN)</td>
</tr>
</tbody>
</table>

<p>Total of each row = all predicted positives (TP + FP) and all predicted negatives (FN + TN)
Total of each column = all real positives (TP + FN) and all real negatives (FP + TN)</p>
<ul><li>When positive examples and negative examples are generally well differentiated, with most positive examples having higher scores than negative examples, the dataset is <strong>separated</strong>.</li>
<li>When the total of actual positives is not close to the total of actual negatives, the dataset is <strong>imbalanced</strong>.</li>
<li>When many positive examples have lower scores than negative examples, and many negative examples have higher scores than positive examples, the dataset is <strong>unseparated</strong>.</li></ul>

<p>When we increase the classification threshold, both TP and FP decrease, and both TN and FN increase.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/classification/thresholding">Thresholds and the confusion matrix | Machine Learning | Google for Developers</a></p>

<h3 id="accuracy-recall-precision-and-related-metrics" id="accuracy-recall-precision-and-related-metrics">Accuracy, recall, precision, and related metrics</h3>

<p>Accuracy, Recall, Precision, and related metrics are all calculated at a single classification threshold value.</p>

<p><strong>Accuracy</strong> is the proportion of all classifications that were correct.
$$
\text{Accuracy} = \frac{\text{correct classifications}}{\text{total classifications}} = \frac{TP+TN}{TP+TN+FP+FN}
$$</p>
<ul><li>Use as a rough indicator of model training progress/convergence for balanced datasets. Typically the default.</li>
<li>For model performance, use only in combination with other metrics.</li>
<li>Avoid for imbalanced datasets. Consider using another metric.</li></ul>

<p><strong>Recall</strong>, or <strong>true positive rate</strong>, is the proportion of all actual positives that were classified correctly as positives. Also known as <strong>probability of detection</strong>.
$$
\text{Recall (or TPR)} = \frac{\text{correctly classified actual positives}}{\text{all actual positives}} = \frac{TP}{TP+FN}
$$</p>
<ul><li>Use when false negatives are more expensive than false positives.</li>
<li>Better than Accuracy in imbalanced datasets.</li>
<li>Improves when false negatives decrease.</li></ul>

<p><strong>False positive rate</strong> is the proportion of all actual negatives that were classified <em>incorrectly</em> as positives. Also known as <strong>probability of a false alarm</strong>.
$$
\text{FPR} = \frac{\text{incorrectly classified actual negatives}}{\text{all actual negatives}}=\frac{FP}{FP+TN}
$$</p>
<ul><li>Use when false positives are more expensive than false negatives.</li>
<li>Less meaningful and useful in a dataset where the number of actual negtives is very, very low.</li></ul>

<p><strong>Precision</strong> is the proportion of all the model&#39;s positive classifications that are actually positive.
$$
\text{Precision} = \frac{\text{correctly classified actual positives}}{\text{everything classified as positive}}=\frac{TP}{TP+FP}
$$</p>
<ul><li>Use when it&#39;s very important for positive predictions to be accurate.</li>
<li>Less meaningful and useful in a dataset where the number of actual positives is very, very low.</li>
<li>Improves as false positives decrease.</li></ul>

<p>Precision and Recall often show an inverse relationship.</p>

<p><strong>F1 score</strong> is the harmonic mean of Precision and Recall.
$$
\text{F1} = 2 * \frac{\text{precision} * \text{recall}}{\text{precision} + \text{recall}} = \frac{2TP}{2TP + FP + FN}
$$</p>
<ul><li>Preferable for class-imbalanced datasets.</li>
<li>When Precision and Recall are close in value, F1 will be close to their value.</li>
<li>When Precision and Recall are far apart, F1 will be similar to whichever metric is worse.</li></ul>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/classification/accuracy-precision-recall">Classification: Accuracy, recall, precision, and related metrics | Machine Learning | Google for Developers</a></p>

<h3 id="roc-and-auc" id="roc-and-auc">ROC and AUC</h3>

<p>ROC and AUC evaluate a model&#39;s quality across all possible thresholds.</p>

<p><strong>ROC curve</strong>, or <strong>receiver operating characteristic curves</strong>, plot the true positive rate (TPR) against the false positive rate (FPR) at different thresholds. A perfect model would pass through (0,1), while a random guesser forms a diagonal line from (0,0) to (1,1).</p>

<p><strong>AUC</strong>, or <strong>area under the curve</strong>, represents the probability that the model will rank a randomly chosen positive example higher than a negative example. A perfect model has AUC = 1.0, while a random model has AUC = 0.5.</p>

<p>ROC and AUC of a hypothetical perfect model (AUC = 1.0) and for completely random guesses (AUC = 0.5):
<img src="https://media.portblue.net/resources/251229_ml-crash-course/auc_1-0.png" alt="auc_1-0.png"/><img src="https://media.portblue.net/resources/251229_ml-crash-course/auc_0-5.png" alt="auc_0-5.png"/></p>

<p>ROC and AUC are effective when class distributions are balanced. For imbalanced data, <strong>precision-recall curves (PRCs)</strong> can be more informative.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/prauc.png" alt="prauc.png"/></p>

<p>A higher AUC generally indicates a better-performing model.</p>

<p>ROC and AUC of two hypothetical models; the first curve (AUC = 0.65) represents the better of the two models:
<img src="https://media.portblue.net/resources/251229_ml-crash-course/auc_0-65.png" alt="auc_0-65.png"/>
<img src="https://media.portblue.net/resources/251229_ml-crash-course/auc_0-93.png" alt="auc_0-93.png"/></p>

<p>Threshold choice depends on the cost of false positives versus false negatives. The most relevant thresholds are those closest to (0,1) on the ROC curve. For costly false positives, a conservative threshold (like A in the chart below) is better. For costly false negatives, a more sensitive threshold (like C) is preferable. If costs are roughly equivalent, a threshold in the middle (like B) may be best.
<img src="https://media.portblue.net/resources/251229_ml-crash-course/auc_abc.png" alt="auc_abc.png"/></p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/classification/roc-and-auc">Classification: ROC and AUC | Machine Learning | Google for Developers</a></p>

<h3 id="prediction-bias" id="prediction-bias">Prediction bias</h3>

<p><strong>Prediction bias</strong> measures the difference between the average of a model&#39;s predictions and the average of the true labels in the data. For example, if 5% of emails in the dataset are spam, a model without prediction bias should also predict about 5% as spam. A large mismatch between these averages indicates potential problems.</p>

<p>Prediction bias can be caused by:</p>
<ul><li>Biased and noisy data (e.g., skewed sampling)</li>
<li>Overly strong regularisation that oversimplifies the model</li>
<li>Bugs in the model training pipeline</li>
<li>Insufficient features provided to the model</li></ul>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/classification/prediction-bias">Classification: Prediction bias | Machine Learning | Google for Developers</a></p>

<h3 id="multi-class-classification" id="multi-class-classification">Multi-class classification</h3>

<p><strong>Multi-class classification</strong> extends binary classification to cases with more than two classes.</p>

<p>If each example belongs to only one class, the problem can be broken down into a series of binary classifications. For instance, with three classes (A, B, C), you could first separate C from A+B, then distinguish A from B within the A+B group.</p>

<p>Source: <a href="https://developers.google.com/machine-learning/crash-course/classification/multiclass">Classification: Multi-class classification | Machine Learning | Google for Developers</a></p>
]]></content:encoded>
      <guid>https://stefan.angrick.me/google-ml-crash-course-1-notes-ml-models</guid>
      <pubDate>Mon, 29 Dec 2025 10:02:39 +0000</pubDate>
    </item>
    <item>
      <title>Notes From Google’s Machine Learning Crash Course</title>
      <link>https://stefan.angrick.me/notes-from-googles-machine-learning-crash-course?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[I like to revisit Google&#39;s Machine Learning Crash Course every now and then to refresh my understanding of key machine learning concepts. It&#39;s a fantastic free resource, published under the Creative Commons Attribution 4.0 License, now updated with content on recent developments like large language models and automated ML.!--more--&#xA;&#xA;I take notes as a personal reference, and I thought I would post them here to keep track of what I&#39;ve learned--while hopefully offering something useful to others doing the same.&#xA;&#xA;The notes are organised into four posts, one for each course module:&#xA;&#xA;Google ML Crash Course #1: ML Models&#xA;Google ML Crash Course #2: Data&#xA;Google ML Crash Course #3: Advanced ML Models&#xA;Google ML Crash Course #4: Real-World ML]]&gt;</description>
      <content:encoded><![CDATA[<p>I like to revisit Google&#39;s <a href="https://developers.google.com/machine-learning/crash-course/">Machine Learning Crash Course</a> every now and then to refresh my understanding of key machine learning concepts. It&#39;s a fantastic free resource, published under the <a href="https://creativecommons.org/licenses/by/4.0/">Creative Commons Attribution 4.0 License</a>, now updated with content on recent developments like large language models and automated ML.</p>

<p>I take notes as a personal reference, and I thought I would post them here to keep track of what I&#39;ve learned—while hopefully offering something useful to others doing the same.</p>

<p>The notes are organised into four posts, one for each course module:</p>
<ol><li><a href="google-ml-crash-course-1-notes-ml-models">Google ML Crash Course #1: ML Models</a></li>
<li><a href="google-ml-crash-course-2-notes-data">Google ML Crash Course #2: Data</a></li>
<li><a href="google-ml-crash-course-3-notes-advanced-ml-models">Google ML Crash Course #3: Advanced ML Models</a></li>
<li><a href="google-ml-crash-course-4-notes-real-world-ml">Google ML Crash Course #4: Real-World ML</a></li></ol>
]]></content:encoded>
      <guid>https://stefan.angrick.me/notes-from-googles-machine-learning-crash-course</guid>
      <pubDate>Mon, 29 Dec 2025 09:20:44 +0000</pubDate>
    </item>
    <item>
      <title>Does Japan Have a Labour Shortage?</title>
      <link>https://stefan.angrick.me/does-japan-have-a-labour-shortage?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[The notion that Japan has a labour shortage is widely accepted. The country&#39;s ageing and shrinking population leaves fewer working-age people for firms to hire. Businesses often cite difficulties finding workers as a reason for raising pay, and labour shortages are seen as a driver of inflation. However, Mizuho executive economist Momma Kazuo, in a commentary published on 21 January 2025, challenges this view. He argues that labour market conditions are more nuanced than commonly perceived and that declining real wages contradict the narrative of a general labour shortage. This post summarises key points from the report.!--more--&#xA;&#xA;A PDF of the original Japanese-language report can be found here.&#xA;&#xA;Nominal wages are increasing&#xA;&#xA;The 2024 shunto spring wage negotiations produced a 5.1% nominal pay gain, the highest in 33 years. Labour unions are aiming for a 5%+ increase in 2025.&#xA;Inflation and labour shortages are widely cited as drivers of wage increases. While inflation is a clear driver of wage gains, the impact of labour shortages is less certain.&#xA;Businesses cite pay increases as necessary to retain workers. But if labour shortages were driving inflation, nominal pay gains would outpace inflation and real wages would rise.&#xA;Real wages briefly increased in summer 2024 but remain 2.4% lower than in 2019.&#xA;To recover this loss by 2026, real wages need to rise 1.2% annually, which requires nominal pay gains of 3.2% assuming 2% inflation. This aligns with shunto outcomes of 5%.&#xA;The modest union wage demands suggest limited negotiating power. True labour shortages would lead to stronger wage demands.&#xA;&#xA;2017 again?&#xA;&#xA;In 2017, wage stagnation was partly attributed to increased employment of women and seniors, who often take lower-wage jobs, reducing average wage levels.&#xA;Workforce growth from these groups has since slowed, leading some to argue that current wage increases reflect genuine labour shortages.&#xA;But the continued stagnation of real wages casts doubt on this argument. It also suggests that wage stagnation in 2017 has yet to be fully explained.&#xA;&#xA;Not really a labour shortage?&#xA;&#xA;Some researchers argue that labour shortages are overstated, including Professor Saito Makoto of Nagoya University and Professor Shioji Etsuro of Chuo University.&#xA;Indicators like the job-to-applicant ratio, the unemployment rate, and the Bank of Japan&#39;s labour supply-demand gap estimate show that the labour market is not as tight as before the pandemic.&#xA;Labour shortages may be sector-specific, with industries like IT, construction, and essential services facing shortages, while others, such as office roles, experience surplus supply.&#xA;&#xA;Financial constraints impeding wage growth&#xA;&#xA;Businesses may lack the financial resources to support significant wage increases.&#xA;Japan&#39;s real GDP growth has been so weak as to suggest that Japan is heading towards four lost decades.&#xA;Weak real GDP growth and worsening terms of trade have eroded Japan&#39;s real Gross Domestic Income (GDI), with ¥5.8 trillion (approximately 1% of GDP) in income flowing out of the economy since 2019.&#xA;This weak macroeconomic environment limits the ability to achieve sustained real wage growth.&#xA;&#xA;Domestic growth expectations are key&#xA;&#xA;Many businesses increasingly rely on price increases to fund wage hikes, but this does not improve real wages as higher costs offset nominal gains.&#xA;Policies to sustainably increase real wages are difficult to identify, but obstacles that need to be resolved include institutional constraints, time and cost barriers to reskilling, a lack of investment in workers, and weak domestic growth expectations.&#xA;&#xA;Links&#xA;&#xA;Momma Kazuo&#39;s research pieces at Mizuho Research &amp; Technologies]]&gt;</description>
      <content:encoded><![CDATA[<p>The notion that Japan has a labour shortage is widely accepted. The country&#39;s ageing and shrinking population leaves fewer working-age people for firms to hire. Businesses often cite difficulties finding workers as a reason for raising pay, and labour shortages are seen as a driver of inflation. However, Mizuho executive economist Momma Kazuo, in a commentary published on 21 January 2025, challenges this view. He argues that labour market conditions are more nuanced than commonly perceived and that declining real wages contradict the narrative of a general labour shortage. This post summarises key points from the report.</p>

<p>A PDF of the original Japanese-language report can be found <a href="https://www.mizuho-rt.co.jp/publication/executive/pdf/km_c250121.pdf">here</a>.</p>

<h2 id="nominal-wages-are-increasing" id="nominal-wages-are-increasing">Nominal wages are increasing</h2>
<ul><li>The 2024 shunto spring wage negotiations produced a 5.1% nominal pay gain, the highest in 33 years. Labour unions are aiming for a 5%+ increase in 2025.</li>
<li>Inflation and labour shortages are widely cited as drivers of wage increases. While inflation is a clear driver of wage gains, the impact of labour shortages is less certain.</li>
<li>Businesses cite pay increases as necessary to retain workers. But if labour shortages were driving inflation, nominal pay gains would outpace inflation and real wages would rise.</li>
<li>Real wages briefly increased in summer 2024 but remain 2.4% lower than in 2019.</li>
<li>To recover this loss by 2026, real wages need to rise 1.2% annually, which requires nominal pay gains of 3.2% assuming 2% inflation. This aligns with shunto outcomes of 5%.</li>
<li>The modest union wage demands suggest limited negotiating power. True labour shortages would lead to stronger wage demands.</li></ul>

<h2 id="2017-again" id="2017-again">2017 again?</h2>
<ul><li>In 2017, wage stagnation was partly attributed to increased employment of women and seniors, who often take lower-wage jobs, reducing average wage levels.</li>
<li>Workforce growth from these groups has since slowed, leading some to argue that current wage increases reflect genuine labour shortages.</li>
<li>But the continued stagnation of real wages casts doubt on this argument. It also suggests that wage stagnation in 2017 has yet to be fully explained.</li></ul>

<h2 id="not-really-a-labour-shortage" id="not-really-a-labour-shortage">Not really a labour shortage?</h2>
<ul><li>Some researchers argue that labour shortages are overstated, including Professor Saito Makoto of Nagoya University and Professor Shioji Etsuro of Chuo University.</li>
<li>Indicators like the job-to-applicant ratio, the unemployment rate, and the Bank of Japan&#39;s labour supply-demand gap estimate show that the labour market is not as tight as before the pandemic.</li>
<li>Labour shortages may be sector-specific, with industries like IT, construction, and essential services facing shortages, while others, such as office roles, experience surplus supply.</li></ul>

<h2 id="financial-constraints-impeding-wage-growth" id="financial-constraints-impeding-wage-growth">Financial constraints impeding wage growth</h2>
<ul><li>Businesses may lack the financial resources to support significant wage increases.</li>
<li>Japan&#39;s real GDP growth has been so weak as to suggest that Japan is heading towards <a href="on-the-brink-of-40-lost-years-momma-kazuos-commentary-on-the-japanese-economy">four lost decades</a>.</li>
<li>Weak real GDP growth and worsening terms of trade have eroded Japan&#39;s real Gross Domestic Income (GDI), with ¥5.8 trillion (approximately 1% of GDP) in income flowing out of the economy since 2019.</li>
<li>This weak macroeconomic environment limits the ability to achieve sustained real wage growth.</li></ul>

<h2 id="domestic-growth-expectations-are-key" id="domestic-growth-expectations-are-key">Domestic growth expectations are key</h2>
<ul><li>Many businesses increasingly rely on price increases to fund wage hikes, but this does not improve real wages as higher costs offset nominal gains.</li>
<li>Policies to sustainably increase real wages are difficult to identify, but obstacles that need to be resolved include institutional constraints, time and cost barriers to reskilling, a lack of investment in workers, and weak domestic growth expectations.</li></ul>

<h2 id="links" id="links">Links</h2>
<ul><li><a href="https://www.mizuho-rt.co.jp/publication/executive/index.html">Momma Kazuo&#39;s research pieces</a> at Mizuho Research &amp; Technologies</li></ul>
]]></content:encoded>
      <guid>https://stefan.angrick.me/does-japan-have-a-labour-shortage</guid>
      <pubDate>Thu, 23 Jan 2025 12:09:25 +0000</pubDate>
    </item>
    <item>
      <title>On the Brink of Four Lost Decades</title>
      <link>https://stefan.angrick.me/on-the-brink-of-40-lost-years-momma-kazuos-commentary-on-the-japanese-economy?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[This post summarises key points from the latest economic commentary by Momma Kazuo, executive economist with Mizuho Research &amp; Technologies and former assistant governor at the Bank of Japan. Published on 25 December 2024, this piece is part of a series of articles exploring issues in the Japanese and global economies. It highlights the risk of Japan&#39;s lost decades continuing and questions whether the country can overcome its demographic challenges.!--more--&#xA;&#xA;A PDF of the original Japanese-language report is available here.&#xA;&#xA;The end of deflation, but no growth&#xA;&#xA;Looking back, 2024 marked the year Japan&#39;s economy exited deflation, as Shunto spring wage negotiations achieved increases exceeding 5% for the first time in 33 years, consumer price inflation surpassed 2% for three consecutive years, and the stock market reached record highs.&#xA;But real GDP growth remains alarmingly sluggish, suggesting that after the &#34;Lost 30 Years,&#34; Japan&#39;s economy is now heading towards a &#34;Lost 40 Years.&#34;&#xA;Since the COVID-19 pandemic, real GDP growth has averaged only 0.2% per year, far below the 0.5% trend growth rate.&#xA;&#xA;Wages and inflation reflect economic problems&#xA;&#xA;Deflation occurs when demand is too weak to utilise available labour and other supply capacities. In Japan, this happened after the bursting of the bubble which made households and businesses turn extremely cautious and unwilling to spend.&#xA;This demand weakness persists but is now exacerbated by supply-side constraints, such as rising import costs and a shrinking workforce due to population ageing.&#xA;Deflation has ended, with wages and prices rising, not because of stronger demand but because supply capacity can no longer meet even weak demand. Labelling this a &#34;virtuous cycle of wages and prices&#34; is an unrealistic and overly optimistic interpretation.&#xA;If a true virtuous cycle were occurring, public opinion surveys by the Bank of Japan would reflect greater optimism about living conditions, and the ruling coalitions&#39; loss in recent general elections would be considered odd.&#xA;&#xA;Stocks and the real economy diverge&#xA;&#xA;Corporations and privileged individuals claim a virtuous cycle is underway because they are relatively well-off, can absorb the rising cost of living, and mistakenly believe higher prices reflect an improved economy due to increased profits and stock gains.&#xA;Nominal GDP growth appears strong, even as real GDP stagnates, but there are two critical considerations.&#xA;First, inflation erodes the value of financial assets.&#xA;Second, stock market gains since the early 2010s are attributable to corporate reforms, as wages, prices, and nominal output showed limited growth during this period.&#xA;Stock prices have risen due to shareholder-focused and profitability-enhancing reforms, such as the elimination of cross-shareholdings, increased influence of foreign investors, and government-led reforms, countering the perception that Abenomics&#39; structural reform agenda was neglected.&#xA;If investors assume Japan&#39;s domestic market will continue shrinking, companies are evaluated primarily on (1) overseas expansion and (2) domestic business efficiency.&#xA;The issue is that (1) overseas expansion is unlikely to translate into domestic investment or wage increases, and (2) efficiency improvements may even have a negative impact.&#xA;This dynamic explains the disconnect between rising stock prices and the stagnation of the domestic economy, particularly among small and medium-sized enterprises and households.&#xA;&#xA;On a genuine virtuous cycle&#xA;&#xA;Ensuring households directly benefit from rising stock prices is one approach, but focusing solely on asset-based measures risks increasing inequality.&#xA;Outright redistribution policies, such as increased taxes on financial income, are impractical as they would disrupt the stock market&#39;s momentum and corporate reform progress.&#xA;There is hope in Japanese companies&#39; inherent resilience and the potential for labour shortages to drive productivity gains, but achieving this requires businesses and shareholders to view domestic market expansion as profitable.&#xA;Initiatives like the TSMC boom in Kyushu demonstrate how government intervention can stimulate virtuous cycles by creating business opportunities, even amid demographic challenges. Economic security was a key driver in this case.&#xA;To avoid another four decades of stagnation, Japan must address critical issues like decarbonisation, developing new energy sources, strengthening science and technology, renewing infrastructure, and reforming education. This requires vision and insight from both the public and private sectors.&#xA;&#xA;Links&#xA;&#xA;Momma Kazuo&#39;s research pieces at Mizuho Research &amp; Technologies]]&gt;</description>
      <content:encoded><![CDATA[<p>This post summarises key points from the latest economic commentary by Momma Kazuo, executive economist with Mizuho Research &amp; Technologies and former assistant governor at the Bank of Japan. Published on 25 December 2024, this piece is part of a series of articles exploring issues in the Japanese and global economies. It highlights the risk of Japan&#39;s lost decades continuing and questions whether the country can overcome its demographic challenges.</p>

<p>A PDF of the original Japanese-language report is available <a href="https://www.mizuho-rt.co.jp/publication/executive/pdf/km_c241225.pdf">here</a>.</p>

<h2 id="the-end-of-deflation-but-no-growth" id="the-end-of-deflation-but-no-growth">The end of deflation, but no growth</h2>
<ul><li>Looking back, 2024 marked the year Japan&#39;s economy exited deflation, as Shunto spring wage negotiations achieved increases exceeding 5% for the first time in 33 years, consumer price inflation surpassed 2% for three consecutive years, and the stock market reached record highs.</li>
<li>But real GDP growth remains alarmingly sluggish, suggesting that after the “Lost 30 Years,” Japan&#39;s economy is now heading towards a “Lost 40 Years.”</li>
<li>Since the COVID-19 pandemic, real GDP growth has averaged only 0.2% per year, far below the 0.5% trend growth rate.</li></ul>

<h2 id="wages-and-inflation-reflect-economic-problems" id="wages-and-inflation-reflect-economic-problems">Wages and inflation reflect economic problems</h2>
<ul><li>Deflation occurs when demand is too weak to utilise available labour and other supply capacities. In Japan, this happened after the bursting of the bubble which made households and businesses turn extremely cautious and unwilling to spend.</li>
<li>This demand weakness persists but is now exacerbated by supply-side constraints, such as rising import costs and a shrinking workforce due to population ageing.</li>
<li>Deflation has ended, with wages and prices rising, not because of stronger demand but because supply capacity can no longer meet even weak demand. Labelling this a “virtuous cycle of wages and prices” is an unrealistic and overly optimistic interpretation.</li>
<li>If a true virtuous cycle were occurring, public opinion surveys by the Bank of Japan would reflect greater optimism about living conditions, and the ruling coalitions&#39; loss in recent general elections would be considered odd.</li></ul>

<h2 id="stocks-and-the-real-economy-diverge" id="stocks-and-the-real-economy-diverge">Stocks and the real economy diverge</h2>
<ul><li>Corporations and privileged individuals claim a virtuous cycle is underway because they are relatively well-off, can absorb the rising cost of living, and mistakenly believe higher prices reflect an improved economy due to increased profits and stock gains.</li>
<li>Nominal GDP growth appears strong, even as real GDP stagnates, but there are two critical considerations.</li>
<li>First, inflation erodes the value of financial assets.</li>
<li>Second, stock market gains since the early 2010s are attributable to corporate reforms, as wages, prices, and nominal output showed limited growth during this period.</li>
<li>Stock prices have risen due to shareholder-focused and profitability-enhancing reforms, such as the elimination of cross-shareholdings, increased influence of foreign investors, and government-led reforms, countering the perception that Abenomics&#39; structural reform agenda was neglected.</li>
<li>If investors assume Japan&#39;s domestic market will continue shrinking, companies are evaluated primarily on (1) overseas expansion and (2) domestic business efficiency.</li>
<li>The issue is that (1) overseas expansion is unlikely to translate into domestic investment or wage increases, and (2) efficiency improvements may even have a negative impact.</li>
<li>This dynamic explains the disconnect between rising stock prices and the stagnation of the domestic economy, particularly among small and medium-sized enterprises and households.</li></ul>

<h2 id="on-a-genuine-virtuous-cycle" id="on-a-genuine-virtuous-cycle">On a genuine virtuous cycle</h2>
<ul><li>Ensuring households directly benefit from rising stock prices is one approach, but focusing solely on asset-based measures risks increasing inequality.</li>
<li>Outright redistribution policies, such as increased taxes on financial income, are impractical as they would disrupt the stock market&#39;s momentum and corporate reform progress.</li>
<li>There is hope in Japanese companies&#39; inherent resilience and the potential for labour shortages to drive productivity gains, but achieving this requires businesses and shareholders to view domestic market expansion as profitable.</li>
<li>Initiatives like the TSMC boom in Kyushu demonstrate how government intervention can stimulate virtuous cycles by creating business opportunities, even amid demographic challenges. Economic security was a key driver in this case.</li>
<li>To avoid another four decades of stagnation, Japan must address critical issues like decarbonisation, developing new energy sources, strengthening science and technology, renewing infrastructure, and reforming education. This requires vision and insight from both the public and private sectors.</li></ul>

<h2 id="links" id="links">Links</h2>
<ul><li><a href="https://www.mizuho-rt.co.jp/publication/executive/index.html">Momma Kazuo&#39;s research pieces</a> at Mizuho Research &amp; Technologies</li></ul>
]]></content:encoded>
      <guid>https://stefan.angrick.me/on-the-brink-of-40-lost-years-momma-kazuos-commentary-on-the-japanese-economy</guid>
      <pubDate>Sun, 29 Dec 2024 00:34:09 +0000</pubDate>
    </item>
    <item>
      <title>Proxying the Yen Carry Trade</title>
      <link>https://stefan.angrick.me/proxying-the-yen-carry-trade?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[The big story over the past two weeks has been the unwinding of the yen carry trade. This trade involves borrowing yen at low rates in Japan and investing the funds in higher-yielding foreign currencies, such as the US dollar or the Mexican peso. Many have argued that a surprise rate hike from the Bank of Japan on 31 July and disappointing US labour market data on 2 August triggered the collapse of this trade. As a result, the yen surged, equities stumbled, and government bonds rallied. While not much is known about the exact scale of the yen carry trade, this post explores two methods of proxying it.px.gif!--more--&#xA;&#xA;Method one: Tracking yen credit to borrowers outside Japan via BIS&#xA;&#xA;One method to track the yen carry trade was suggested by Hyun Song Shin, Economic Adviser and Head of Research at the Bank for International Settlements (BIS), in a Twitter/X thread on 9 August. Shin pointed to the BIS Global Liquidity Indicators data Q.JPY.3P.N.B.I.G.JPY, which is quarterly data that tracks yen-denominated loans as foreign currency, excluding yen securities. By the end of March 2024, these loans tallied just above 41 trillion JPY, up from about 30 trillion pre-pandemic. Shin notes that not all of this reflects carry trade activity, so this figure should be considered a ceiling for carry trades conducted on-balance sheet.&#xA;&#xA;bisyencredityencarry.png&#xA;&#xA;Shin further explains that carry trades can also be done through FX swaps, where a lender provides dollars in return for yen. The dollar provider normally parks the yen proceeds in a safe yen asset, such as short-term Japanese government bonds. But if the dollar provider instead sells the yen proceeds in the spot market for dollars, it leaves an unhedged yen obligation, which constitutes a carry trade that isn&#39;t captured in BIS data. Shin points to this study, which puts the size of dollar/yen FX swaps at around 14 trillion USD, with about 1 trillion USD held by foreigners in official assets.&#xA;&#xA;Method two: Monitoring foreign bank borrowing from Tokyo offices via BOJ&#xA;&#xA;Another method for proxying the yen carry trade that is popular in Japan is monitoring foreign banks&#39; borrowing from their Tokyo offices. A bank with a global presence can raise yen through its Tokyo branch. When that happens, the Tokyo office acquires a claim on the foreign office through interoffice accounts. This data is available at monthly frequency through the Bank of Japan&#39;s release on Principal Assets and Liabilities of Foreign Banks in Japan data BS02&#39;FAFBKFAFB2A9. As of May 2024, foreign borrowing from Tokyo offices was about 11 trillion JPY, up from about 7.5 trillion pre-pandemic.&#xA;&#xA;bojfrgnbankborrowingyencarry.png&#xA;&#xA;Here is an R script to produce the charts above.&#xA;&#xA;Update (1 September 2024): The BIS has released new analysis on the carry trade unwind, which shows additional data for yen claims on non-banks in offshore centres. This data is part of the Locational Banking Statistics and can be compiled by summing up the figures for offshore economies, starting with the Cayman Islands under the code Q.S.C.A.JPY.A.5J.A.5A.N.KY.N. Alternatively, you can visit the Bank of Japan&#39;s statistics portal and download the flat file for BIS International Locational Banking Statistics in Japan (Claims), which contains the relevant totals under indicator codes BIS3G00103203200071N and BIS3G00303203200071N.&#xA;&#xA;Links&#xA;&#xA;Adam Tooze&#39;s Chartbook 305 Yen carry trades and the turmoil in global fx and equity markets&#xA;Bloomberg Odd Lots podcast episode Lots More on Solving the Mystery of the Big Market Selloff, featuring Charlie McElligott, cross-asset macro strategist at Nomura&#xA;Wall Street Journal article What Is the Yen Carry Trade?&#xA;The Economist article Time to shine a light on the shadowy carry trade&#xA;Nikkei article Is the yen carry trade the culprit behind the stock market crash? (Japanese)]]&gt;</description>
      <content:encoded><![CDATA[<p>The big story over the past two weeks has been the unwinding of the yen carry trade. This trade involves borrowing yen at low rates in Japan and investing the funds in higher-yielding foreign currencies, such as the US dollar or the Mexican peso. Many have argued that a surprise rate hike from the Bank of Japan on 31 July and disappointing US labour market data on 2 August triggered the collapse of this trade. As a result, the yen surged, equities stumbled, and government bonds rallied. While not much is known about the exact scale of the yen carry trade, this post explores two methods of proxying it.<img src="https://media.portblue.net/resources/px.gif" alt="px.gif"/></p>

<h2 id="method-one-tracking-yen-credit-to-borrowers-outside-japan-via-bis" id="method-one-tracking-yen-credit-to-borrowers-outside-japan-via-bis">Method one: Tracking yen credit to borrowers outside Japan via BIS</h2>

<p>One method to track the yen carry trade was suggested by Hyun Song Shin, Economic Adviser and Head of Research at the Bank for International Settlements (BIS), in a <a href="https://x.com/HyunSongShin/status/1821905766439076224">Twitter/X thread</a> on 9 August. Shin pointed to the BIS Global Liquidity Indicators data <a href="https://data.bis.org/topics/GLI/BIS,WS_GLI,1.0/Q.JPY.3P.N.B.I.G.JPY">Q.JPY.3P.N.B.I.G.JPY</a>, which is quarterly data that tracks yen-denominated loans as foreign currency, excluding yen securities. By the end of March 2024, these loans tallied just above 41 trillion JPY, up from about 30 trillion pre-pandemic. Shin notes that not all of this reflects carry trade activity, so this figure should be considered a ceiling for carry trades conducted on-balance sheet.</p>

<p><img src="https://media.portblue.net/resources/240818_yen-carry-trade/bis_yen_credit_yen_carry.png" alt="bis_yen_credit_yen_carry.png"/></p>

<p>Shin further explains that carry trades can also be done through FX swaps, where a lender provides dollars in return for yen. The dollar provider normally parks the yen proceeds in a safe yen asset, such as short-term Japanese government bonds. But if the dollar provider instead sells the yen proceeds in the spot market for dollars, it leaves an unhedged yen obligation, which constitutes a carry trade that isn&#39;t captured in BIS data. Shin points to <a href="https://www.bis.org/publ/qtrpdf/r_qt2309b.htm">this study</a>, which puts the size of dollar/yen FX swaps at around 14 trillion USD, with about 1 trillion USD held by foreigners in official assets.</p>

<h2 id="method-two-monitoring-foreign-bank-borrowing-from-tokyo-offices-via-boj" id="method-two-monitoring-foreign-bank-borrowing-from-tokyo-offices-via-boj">Method two: Monitoring foreign bank borrowing from Tokyo offices via BOJ</h2>

<p>Another method for proxying the yen carry trade that is popular in Japan is monitoring foreign banks&#39; borrowing from their Tokyo offices. A bank with a global presence can raise yen through its Tokyo branch. When that happens, the Tokyo office acquires a claim on the foreign office through interoffice accounts. This data is available at monthly frequency through the Bank of Japan&#39;s release on <a href="https://www.boj.or.jp/en/statistics/outline/note/notest32.htm">Principal Assets and Liabilities of Foreign Banks in Japan</a> data <a href="https://www.stat-search.boj.or.jp/index_en.html">BS02&#39;FAFBK_FAFB2A9</a>. As of May 2024, foreign borrowing from Tokyo offices was about 11 trillion JPY, up from about 7.5 trillion pre-pandemic.</p>

<p><img src="https://media.portblue.net/resources/240818_yen-carry-trade/boj_frgn_bank_borrowing_yen_carry.png" alt="boj_frgn_bank_borrowing_yen_carry.png"/></p>

<p><a href="https://media.portblue.net/resources/240818_yen-carry-trade/yen_carry_trade.R">Here</a> is an R script to produce the charts above.</p>

<p><em>Update (1 September 2024): The BIS has released new <a href="https://www.bis.org/publ/bisbull90.htm">analysis</a> on the carry trade unwind, which shows additional data for yen claims on non-banks in offshore centres. This data is part of the Locational Banking Statistics and can be compiled by summing up the figures for offshore economies, starting with the Cayman Islands under the code <a href="Q.S.C.A.JPY.A.5J.A.5A.N.KY.N">Q.S.C.A.JPY.A.5J.A.5A.N.KY.N</a>. Alternatively, you can visit the Bank of Japan&#39;s <a href="https://www.stat-search.boj.or.jp/info/dload_en.html">statistics portal</a> and download the flat file for <a href="https://www.stat-search.boj.or.jp/info/bis1-1_q_en.zip">BIS International Locational Banking Statistics in Japan (Claims)</a>, which contains the relevant totals under indicator codes BIS3G00103203200071N and BIS3G00303203200071N.</em></p>

<h2 id="links" id="links">Links</h2>
<ul><li>Adam Tooze&#39;s <a href="https://adamtooze.substack.com/p/chartbook-305-yen-carry-trades-and">Chartbook 305 Yen carry trades and the turmoil in global fx and equity markets</a></li>
<li>Bloomberg Odd Lots podcast episode <a href="https://podcasts.apple.com/us/podcast/lots-more-on-solving-the-mystery-of-the-big-market-selloff/id1056200096?i=1000664508917">Lots More on Solving the Mystery of the Big Market Selloff</a>, featuring Charlie McElligott, cross-asset macro strategist at Nomura</li>
<li>Wall Street Journal article <a href="https://www.wsj.com/finance/currencies/what-is-the-yen-carry-trade-e5ab9670">What Is the Yen Carry Trade?</a></li>
<li>The Economist article <a href="https://www.economist.com/leaders/2024/08/15/time-to-shine-a-light-on-the-shadowy-carry-trade">Time to shine a light on the shadowy carry trade</a></li>
<li>Nikkei article <a href="https://www.nikkei.com/article/DGXZQOUB0925S0Z00C24A8000000/">Is the yen carry trade the culprit behind the stock market crash? (Japanese)</a></li></ul>
]]></content:encoded>
      <guid>https://stefan.angrick.me/proxying-the-yen-carry-trade</guid>
      <pubDate>Sun, 18 Aug 2024 10:57:22 +0000</pubDate>
    </item>
    <item>
      <title>Measuring Expected Inflation with Breakevens</title>
      <link>https://stefan.angrick.me/measuring-expected-inflation-with-breakevens?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[Central banks in recent years have paid close attention to &#34;inflation expectations&#34; when setting monetary policy. But measuring these expectations is not always straightforward. Expectations can vary significantly depending on whether they are drawn from businesses, households, or professional forecasters. One of the more practical methods for gauging inflation expectations is by analysing bond market data. This post provides an overview of how this works.px.gif!--more--&#xA;&#xA;Bond market-based measures of inflation expectations are known as &#34;breakevens&#34;. These breakeven rates offer a snapshot of what investors anticipate inflation will be over a specific timeframe. To calculate a breakeven rate, we compare the yield of an inflation-protected government bond (such as US TIPS) with a nominal government bond of the same maturity. The difference between these two yields represents the breakeven inflation rate, or the rate at which an investor would earn the same return whether they bought an inflation-protected bond or a nominal bond.&#xA;&#xA;Examples&#xA;&#xA;Using data from the U.S. 5-year Treasuries available on the St. Louis Fed&#39;s FRED database, we calculate the breakeven rate as follows:&#xA;&#xA;5-Year Breakeven Inflation Rate (T5YIE) = Yield on 5-year US Treasury (DGS5) - Yield on 5-year US Treasury Inflation-Indexed (DFII5)&#xA;&#xA;As of 8 August 2024, the yield on a 5-year US Treasury is 3.83%, while the yield on an inflation-indexed 5-year US Treasury stands at 1.85%. This translates to a breakeven rate of 1.98% (3.83% - 1.85%).&#xA;&#xA;breakeven5yr.png&#xA;&#xA;Let&#39;s repeat this for 10-year US Treasuries:&#xA;&#xA;10-Year Breakeven Inflation Rate (T10YIE) = Yield on 10-year US Treasury (DGS10) - Yield on 10-year US Treasury Inflation-Indexed (DFII10)&#xA;&#xA;As of 8 August 2024, the yield on a 10-year US Treasury is 3.99%, while the yield on an inflation-indexed 10-year US Treasury is 1.87%. This yields a breakeven rate of 2.12% (3.99% - 1.87%).&#xA;&#xA;breakeven10yr.png&#xA;&#xA;Links&#xA;&#xA;FRED data for US breakeven inflation rates: 5-year breakeven, 7-year breakeven, 10-year breakeven, 20-year breakeven, and 30-year breakeven&#xA;FRED blog post on Measuring expected inflation with breakevens&#xA;Brad DeLong blog post on The Bond Market Thinks a Possible Return to Secular Stagnation Has Just Entered the Chat]]&gt;</description>
      <content:encoded><![CDATA[<p>Central banks in recent years have paid close attention to “inflation expectations” when setting monetary policy. But measuring these expectations is not always straightforward. Expectations can vary significantly depending on whether they are drawn from businesses, households, or professional forecasters. One of the more practical methods for gauging inflation expectations is by analysing bond market data. This post provides an overview of how this works.<img src="https://media.portblue.net/resources/px.gif" alt="px.gif"/></p>

<p>Bond market-based measures of inflation expectations are known as “breakevens”. These breakeven rates offer a snapshot of what investors anticipate inflation will be over a specific timeframe. To calculate a breakeven rate, we compare the yield of an inflation-protected government bond (such as <a href="https://en.wikipedia.org/wiki/United_States_Treasury_security#TIPS">US TIPS</a>) with a nominal government bond of the same maturity. The difference between these two yields represents the breakeven inflation rate, or the rate at which an investor would earn the same return whether they bought an inflation-protected bond or a nominal bond.</p>

<h2 id="examples" id="examples">Examples</h2>

<p>Using data from the U.S. 5-year Treasuries available on the <a href="https://fred.stlouisfed.org/">St. Louis Fed&#39;s FRED database</a>, we calculate the breakeven rate as follows:</p>

<p>5-Year Breakeven Inflation Rate (<a href="https://fred.stlouisfed.org/series/T5YIE">T5YIE</a>) = Yield on 5-year US Treasury (<a href="https://fred.stlouisfed.org/series/DGS5">DGS5</a>) – Yield on 5-year US Treasury Inflation-Indexed (<a href="https://fred.stlouisfed.org/series/DFII5">DFII5</a>)</p>

<p>As of 8 August 2024, the yield on a 5-year US Treasury is 3.83%, while the yield on an inflation-indexed 5-year US Treasury stands at 1.85%. This translates to a breakeven rate of 1.98% (3.83% – 1.85%).</p>

<p><a href="https://fred.stlouisfed.org/graph/?g=JlHQ"><img src="https://media.portblue.net/resources/240811_breakeven-inflation/breakeven5yr.png" alt="breakeven5yr.png"/></a></p>

<p>Let&#39;s repeat this for 10-year US Treasuries:</p>

<p>10-Year Breakeven Inflation Rate (<a href="https://fred.stlouisfed.org/series/T10YIE">T10YIE</a>) = Yield on 10-year US Treasury (<a href="https://fred.stlouisfed.org/series/DGS10">DGS10</a>) – Yield on 10-year US Treasury Inflation-Indexed (<a href="https://fred.stlouisfed.org/series/DFII10">DFII10</a>)</p>

<p>As of 8 August 2024, the yield on a 10-year US Treasury is 3.99%, while the yield on an inflation-indexed 10-year US Treasury is 1.87%. This yields a breakeven rate of 2.12% (3.99% – 1.87%).</p>

<p><a href="https://fred.stlouisfed.org/graph/?g=1rNRy"><img src="https://media.portblue.net/resources/240811_breakeven-inflation/breakeven10yr.png" alt="breakeven10yr.png"/></a></p>

<h2 id="links" id="links">Links</h2>
<ul><li>FRED data for US breakeven inflation rates: <a href="https://fred.stlouisfed.org/series/T5YIE">5-year breakeven</a>, <a href="https://fred.stlouisfed.org/series/T7YIEM">7-year breakeven</a>, <a href="https://fred.stlouisfed.org/series/T10YIE">10-year breakeven</a>, <a href="https://fred.stlouisfed.org/series/T20YIEM">20-year breakeven</a>, and <a href="https://fred.stlouisfed.org/series/T30YIEM">30-year breakeven</a></li>
<li>FRED blog post on <a href="https://fredblog.stlouisfed.org/2021/12/measuring-expected-inflation-with-breakevens/">Measuring expected inflation with breakevens</a></li>
<li>Brad DeLong blog post on <a href="https://braddelong.substack.com/p/the-bond-market-thinks-a-possible">The Bond Market Thinks a Possible Return to Secular Stagnation Has Just Entered the Chat</a></li></ul>
]]></content:encoded>
      <guid>https://stefan.angrick.me/measuring-expected-inflation-with-breakevens</guid>
      <pubDate>Sun, 11 Aug 2024 08:36:23 +0000</pubDate>
    </item>
    <item>
      <title>Estimating the Scale of Japanese Foreign Exchange Intervention</title>
      <link>https://stefan.angrick.me/estimating-the-scale-of-japanese-foreign-exchange-intervention?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[Japanese FX intervention has been in the headlines lately, as the yen&#39;s depreciation has prompted Japanese authorities to step into the market multiple times over the past two years. According to media reports, the Ministry of Finance and the Bank of Japan likely intervened this past Thursday, 11 July, which saw the yen surge from nearly 162 JPY/USD to almost 157 JPY/USD. Official confirmation of the intervention won&#39;t arrive until 31 July, but we can estimate the scale of the intervention using BOJ accounts and money market broker forecasts.px.gif!--more--&#xA;&#xA;Pinpoint the relevant dates&#xA;&#xA;Spot FX interventions settle two business days after the transaction date. If the authorities intervened late on Thursday, 11 July, the corresponding settlement date would be Tuesday, 16 July, since Monday, 15 July, was a public holiday in Japan.&#xA;&#xA;Check money broker forecasts&#xA;&#xA;Next, check money broker forecasts for interbank liquidity due to fiscal factors (財政) on the settlement date. University of Tokyo Professor Hattori Takahiro provides a summary of projections from the three major money broker firms:&#xA;&#xA;Ueda Yagi: 200 billion JPY&#xA;Central Tanshi: 400 billion JPY&#xA;Tokyo Tanshi: 500 billion JPY&#xA;&#xA;Note that these figures are typically expressed in hundreds of millions (億円). Averaging across all three forecasts, we get a surplus of 367 billion JPY.&#xA;&#xA;Check BOJ figures&#xA;&#xA;Now check the BOJ&#39;s projections for changes in interbank liquidity due to fiscal factors (財政等要因) on the settlement date. The BOJ publishes this data in three stages: a forecast one business day in advance, a tentative figure on the day itself, and a revised figure the following business day. The current forecast for 16 July shows a 3,170 billion JPY deficit, as reported here.&#xA;&#xA;Calculate the difference&#xA;&#xA;To estimate the amount involved in the intervention, calculate:&#xA;&#xA;BOJ figure - Money broker forecasts = Estimated scale of intervention&#xA;&#xA;Using the available data, we get:&#xA;&#xA;-3,170 - 367 = -3,537 billion JPY&#xA;&#xA;This suggests the MOF and BOJ likely spent about 3.5 trillion JPY to support the yen—roughly 22 billion USD. This estimate aligns with reports by Bloomberg, Nikkei, and Professor Hattori.&#xA;&#xA;Update (10 August 2024): The latest BOJ data, both tentative and revised, now show a deficit of -2,960 billion JPY. Based on this update, the estimated intervention falls to -3,327 billion JPY.&#xA;&#xA;Update (19 April 2025): The latest official MOF data confirming the intervention shows that the government sold USD and bought JPY to the tune of 3,167.8 billion JPY, which is close to our estimate.&#xA;&#xA;Summary&#xA;&#xA;| FX intervention                                                                                                                           |            |&#xA;| --------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |&#xA;| Intervention and settlement dates                                                                                                         | Dates  |&#xA;| Intervention date                                                                                                                             | 2024/07/11 |&#xA;| Settlement date                                                                                                                               | 2024/07/16 |&#xA;| (1) Money broker forecasts for settlement date                                                                                            | JPY bn |&#xA;| Ueda Tanshi                                                                                | 200.0      |&#xA;| Central Tanshi                                                 | 400.0      |&#xA;| Tokyo Tanshi                                                         | 400.0      |&#xA;| Average                                                                                                                                       | 333.3      |&#xA;| (2) BoJ figures for settlement date                                                                                                       | JPY bn |&#xA;| Forecast                                                                                | -3,170.0   |&#xA;| Preliminary                                                                             | -2,960.0   |&#xA;| Revised                                                                                 | -2,960.0   |&#xA;| Estimated FX intervention = (1) – (2)                                                                                                     | JPY bn |&#xA;| Based on BoJ forecast                                                                                                                         | 3,503.3    |&#xA;| Based on BoJ preliminary                                                                                                                      | 3,293.3    |&#xA;| Based on BoJ revised                                                                                                                          | 3,293.3    |&#xA;| Reported FX intervention                                                                                                                  | JPY bn |&#xA;| JPY bought, USD sold | 3,167.8    |&#xA;&#xA;Links&#xA;&#xA;Official MOF data reporting FX intervention can be found here or here (Japanese)&#xA;The release schedule for official MOF reports can be found here (Japanese)&#xA;The BOJ reports sources of changes in its current account balances here (Japanese)&#xA;Daily Ueda Yagi money market broker reports can be found here (Japanese)&#xA;Daily Central Tanshi money market broker reports can be found here (Japanese)&#xA;Daily Tokyo Tanshi money market broker reports can be found here (Japanese)&#xA;Asahi TV post on X/Twitter highlighting the suspected intervention&#xA;A Bloomberg report from 12 July quoting Tokyo Tanshi forecast as 400 billion JPY]]&gt;</description>
      <content:encoded><![CDATA[<p>Japanese FX intervention has been in the headlines lately, as the yen&#39;s depreciation has prompted Japanese authorities to step into the market multiple times over the past two years. According to media reports, the Ministry of Finance and the Bank of Japan likely intervened this past Thursday, 11 July, which saw the yen surge from nearly 162 JPY/USD to almost 157 JPY/USD. Official confirmation of the intervention won&#39;t arrive until 31 July, but we can estimate the scale of the intervention using BOJ accounts and money market broker forecasts.<img src="https://media.portblue.net/resources/px.gif" alt="px.gif"/></p>

<h2 id="pinpoint-the-relevant-dates" id="pinpoint-the-relevant-dates">Pinpoint the relevant dates</h2>

<p>Spot FX interventions settle two business days after the transaction date. If the authorities intervened late on Thursday, 11 July, the corresponding settlement date would be <strong>Tuesday, 16 July</strong>, since Monday, 15 July, was a public holiday in Japan.</p>

<h2 id="check-money-broker-forecasts" id="check-money-broker-forecasts">Check money broker forecasts</h2>

<p>Next, check money broker forecasts for interbank liquidity due to fiscal factors (財政) on the settlement date. University of Tokyo Professor Hattori Takahiro provides a <a href="https://note.com/hattori0819/n/ncac8722b6d05">summary</a> of projections from the three major money broker firms:</p>
<ul><li><a href="https://www.uedayagi.com/dailysignal/2024-7-11/">Ueda Yagi</a>: 200 billion JPY</li>
<li><a href="https://www.central-tanshi.com/market/marketpdf/daily/centdaily20240711.pdf">Central Tanshi</a>: 400 billion JPY</li>
<li><a href="https://www.tokyotanshi.co.jp/archives/market_report/daily/2024-07-11">Tokyo Tanshi</a>: 500 billion JPY</li></ul>

<p>Note that these figures are typically expressed in hundreds of millions (億円). Averaging across all three forecasts, we get a surplus of 367 billion JPY.</p>

<h2 id="check-boj-figures" id="check-boj-figures">Check BOJ figures</h2>

<p>Now check the BOJ&#39;s projections for changes in interbank liquidity due to fiscal factors (財政等要因) on the settlement date. The BOJ <a href="https://www3.boj.or.jp/market/jp/menu.htm">publishes this data</a> in three stages: a forecast one business day in advance, a tentative figure on the day itself, and a revised figure the following business day. The current forecast for 16 July shows a 3,170 billion JPY deficit, as reported <a href="https://www3.boj.or.jp/market/jp/stat/jp240716.htm">here</a>.</p>

<h2 id="calculate-the-difference" id="calculate-the-difference">Calculate the difference</h2>

<p>To estimate the amount involved in the intervention, calculate:</p>

<p>BOJ figure – Money broker forecasts = Estimated scale of intervention</p>

<p>Using the available data, we get:</p>

<p>-3,170 – 367 = -3,537 billion JPY</p>

<p>This suggests the MOF and BOJ likely spent about 3.5 trillion JPY to support the yen—roughly 22 billion USD. This estimate aligns with reports by <a href="https://www.bloomberg.com/news/articles/2024-07-12/BOJ-accounts-suggest-japan-intervened-to-boost-yen-after-us-cpi">Bloomberg</a>, <a href="https://www.nikkei.com/article/DGXZQOUB123PE0S4A710C2000000/">Nikkei</a>, and <a href="https://note.com/hattori0819/n/n5aa715ca5666">Professor Hattori</a>.</p>

<p><em>Update (10 August 2024): The <a href="https://www3.boj.or.jp/market/jp/stat/jd240716.htm">latest BOJ data</a>, both tentative and revised, now show a deficit of -2,960 billion JPY. Based on this update, the estimated intervention falls to -3,327 billion JPY.</em></p>

<p><em>Update (19 April 2025): The <a href="https://www.mof.go.jp/english/policy/international_policy/reference/feio/foreign_exchange_intervention_operations.csv">latest official MOF data</a> confirming the intervention shows that the government sold USD and bought JPY to the tune of 3,167.8 billion JPY, which is close to our estimate.</em></p>

<h2 id="summary" id="summary">Summary</h2>

<table>
<thead>
<tr>
<th><strong>FX intervention</strong></th>
<th></th>
</tr>
</thead>

<tbody>
<tr>
<td><strong>Intervention and settlement dates</strong></td>
<td><strong>Dates</strong></td>
</tr>

<tr>
<td>Intervention date</td>
<td>2024/07/11</td>
</tr>

<tr>
<td>Settlement date</td>
<td>2024/07/16</td>
</tr>

<tr>
<td><strong>(1) Money broker forecasts for settlement date</strong></td>
<td><strong>JPY bn</strong></td>
</tr>

<tr>
<td><a href="https://www.uedayagi.com/dailysignal/2024-7-11/">Ueda Tanshi</a></td>
<td>200.0</td>
</tr>

<tr>
<td><a href="https://www.central-tanshi.com/market/marketpdf/daily/centdaily20240711.pdf">Central Tanshi</a></td>
<td>400.0</td>
</tr>

<tr>
<td><a href="https://www.tokyotanshi.co.jp/archives/market_report/daily/2024-07-11">Tokyo Tanshi</a></td>
<td>400.0</td>
</tr>

<tr>
<td>Average</td>
<td>333.3</td>
</tr>

<tr>
<td><strong>(2) BoJ figures for settlement date</strong></td>
<td><strong>JPY bn</strong></td>
</tr>

<tr>
<td><a href="https://www3.boj.or.jp/market/jp/stat/jd240716.htm">Forecast</a></td>
<td>-3,170.0</td>
</tr>

<tr>
<td><a href="https://www3.boj.or.jp/market/jp/stat/jd240716.htm">Preliminary</a></td>
<td>-2,960.0</td>
</tr>

<tr>
<td><a href="https://www3.boj.or.jp/market/jp/stat/jd240716.htm">Revised</a></td>
<td>-2,960.0</td>
</tr>

<tr>
<td><strong>Estimated FX intervention = (1) – (2)</strong></td>
<td><strong>JPY bn</strong></td>
</tr>

<tr>
<td>Based on BoJ forecast</td>
<td>3,503.3</td>
</tr>

<tr>
<td>Based on BoJ preliminary</td>
<td>3,293.3</td>
</tr>

<tr>
<td>Based on BoJ revised</td>
<td>3,293.3</td>
</tr>

<tr>
<td><strong>Reported FX intervention</strong></td>
<td><strong>JPY bn</strong></td>
</tr>

<tr>
<td><a href="https://www.mof.go.jp/english/policy/international_policy/reference/feio/foreign_exchange_intervention_operations.csv">JPY bought, USD sold</a></td>
<td>3,167.8</td>
</tr>
</tbody>
</table>

<h2 id="links" id="links">Links</h2>
<ul><li>Official MOF data reporting FX intervention can be found <a href="https://www.mof.go.jp/english/policy/international_policy/reference/feio/index.html">here</a> or <a href="https://www.mof.go.jp/policy/international_policy/reference/feio/data/index.html">here (Japanese)</a></li>
<li>The release schedule for official MOF reports can be found <a href="https://www.mof.go.jp/policy/international_policy/reference/feio/index.html">here (Japanese)</a></li>
<li>The BOJ reports sources of changes in its current account balances <a href="https://www3.boj.or.jp/market/jp/menu.htm">here (Japanese)</a></li>
<li>Daily Ueda Yagi money market broker reports can be found <a href="https://www.uedayagi.com/dailysignal/">here (Japanese)</a></li>
<li>Daily Central Tanshi money market broker reports can be found <a href="https://www.central-tanshi.com/market/short-termdailypast.html">here (Japanese)</a></li>
<li>Daily Tokyo Tanshi money market broker reports can be found <a href="https://www.tokyotanshi.co.jp/market_report/daily.html">here (Japanese)</a></li>
<li><a href="https://x.com/tv_asahi_news/status/1811394631265120301">Asahi TV post on X/Twitter</a> highlighting the suspected intervention</li>
<li>A <a href="https://www.bloomberg.co.jp/news/articles/2024-07-12/SGHHO4T1UM0W00">Bloomberg report from 12 July</a> quoting Tokyo Tanshi forecast as 400 billion JPY</li></ul>
]]></content:encoded>
      <guid>https://stefan.angrick.me/estimating-the-scale-of-japanese-foreign-exchange-intervention</guid>
      <pubDate>Mon, 15 Jul 2024 07:00:53 +0000</pubDate>
    </item>
  </channel>
</rss>