<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mihai Timoficiuc on Medium]]></title>
        <description><![CDATA[Stories by Mihai Timoficiuc on Medium]]></description>
        <link>https://medium.com/@mihaitimoficiuc?source=rss-2574d7bfbf34------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bMREI_CveO0WHxE1qrFIfA.png</url>
            <title>Stories by Mihai Timoficiuc on Medium</title>
            <link>https://medium.com/@mihaitimoficiuc?source=rss-2574d7bfbf34------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 14:18:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mihaitimoficiuc/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Predicting Jet Engine Failures with NASA’s C-MAPSS Dataset and LSTM]]></title>
            <link>https://medium.com/@mihaitimoficiuc/predicting-jet-engine-failures-with-nasas-c-mapss-dataset-and-lstm-a-practical-guide-to-85b9513ea9ed?source=rss-2574d7bfbf34------2</link>
            <guid isPermaLink="false">https://medium.com/p/85b9513ea9ed</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[jet-engine]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[predictive-maintenance]]></category>
            <dc:creator><![CDATA[Mihai Timoficiuc]]></dc:creator>
            <pubDate>Sat, 11 Oct 2025 12:02:15 GMT</pubDate>
            <atom:updated>2025-10-12T16:34:26.117Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vp1en5V1Z_V1hCb5A9nc6A.png" /></figure><p><strong>Predictive maintenance</strong> is a maintenance strategy where you use data and machine learning to <em>predict when a machine will fail, </em>so you can repair it <em>before</em> it actually breaks.</p><p>It’s used everywhere from factory assembly lines, where an unexpected machine failure can halt production and cost thousands (not good), to jet engine maintenance, where a single undetected fault could compromise an entire mission or national security (even less good).</p><p>Modern defense isn’t just about combat, it’s about <strong>operational resilience</strong>: keeping jets, radars, and logistics systems ready at any moment.</p><p>I recently came across <a href="https://c3.ai/"><strong>C3.ai</strong></a>, a company working with the U.S. Air Force to monitor and predict equipment failures across their fleet. The idea that AI can <em>keep a nation’s aircraft operational</em> with up to 85% time reduction from aircraft data extract to alert analysis is quite interesting to put it like that.</p><p>This project is my small exploration into that world: using NASA’s turbofan engine data to predict when a jet engine is about to fail, before it does.</p><p>As always <a href="https://github.com/MTimo27/jet-engines-predictive-maintenance">here</a> is the complete repo.</p><h3>Step 1: Data</h3><p>I chose the <a href="https://data.nasa.gov/dataset/cmapss-jet-engine-simulated-data">NASA C-MAPSS dataset, specifically FD001</a>. This is simulated turbofan engine data from NASA’s 2008 PHM competition, and it’s basically the benchmark for testing predictive maintenance algorithms.</p><p>The setup: 100 engines running until they break (training set), and 100 engines that stop mid-flight (test set). Your job? Predict how many cycles each test engine has left.</p><p>Each engine has 21 sensors tracking temperature, pressure, vibration, etc., plus 3 operational settings (altitude, Mach, throttle). The data comes with sensor noise and random manufacturing wear, just like real life. Cool…let’s see:</p><p>FD001 it’s the simplest: sea-level only, single fault mode (High Pressure Compressor degradation). Let’s not overcomplicate things :)</p><p>Data format: 26 space-separated columns, no headers (thanks NASA). Each row is one flight cycle</p><h3>What We’re Loading</h3><pre>columns = [&#39;unit_id&#39;, &#39;time_cycles&#39;, &#39;op_setting_1&#39;, &#39;op_setting_2&#39;, &#39;op_setting_3&#39;] + \<br>          [f&#39;sensor_{i}&#39; for i in range(1, 22)]</pre><p>NASA C-MAPSS dataset doesn’t come with column headers (it’s just raw space-separated numbers in .txt files), so we have to manually define them:</p><ul><li><strong>unit_id</strong>: Which engine (think of it as serial number)</li><li><strong>time_cycles</strong>: Flight cycles elapsed (like an odometer for planes)</li><li><strong>op_setting_1, op_setting_2, op_setting_3</strong>: Operating conditions (altitude, Mach number, throttle resolver angle, basically how the engine is being flown)</li><li><strong>sensor_1 through sensor_21</strong>: Temperature, pressure, vibration readings, etc. (21 different sensors monitoring engine health)</li></ul><h3>How We’re Loading</h3><pre>train = pd.read_csv(os.path.join(DATA_PATH, &#39;train_FD001.txt&#39;), sep=r&#39;\s+&#39;, header=None, names=columns)<br>test = pd.read_csv(os.path.join(DATA_PATH, &#39;test_FD001.txt&#39;), sep=r&#39;\s+&#39;, header=None, names=columns)<br>rul_test = pd.read_csv(os.path.join(DATA_PATH, &#39;RUL_FD001.txt&#39;), sep=r&#39;\s+&#39;, header=None, names=[&#39;RUL&#39;])</pre><p>Why <em>sep=r’\s+’</em>? The NASA data uses inconsistent whitespace (sometimes spaces, sometimes tabs), <em>\s+</em> means “one or more whitespace characters” basically, split on any amount of whitespace. The <em>r prefix</em> makes it a raw string so Python doesn’t get confused by backslashes.</p><p>Three files:<br> 1. train_FD001.txt: Run-to-failure trajectories (engines that ran until they broke)<br> 2. test_FD001.txt: Engines mid-life (stopped before failure)<br> 3. RUL_FD001.txt: Ground truth, actual remaining cycles for test engines</p><p><strong>What does RUL even mean? RUL = Remaining Useful Life</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*DFuFOxxV8meQW5ku_gUbew.png" /><figcaption>Figure: Engine Lifetime Distribution in the NASA C-MAPSS Dataset</figcaption></figure><p>It’s the number of cycles (or flight hours) an engine has left before it fails. (e.g. RUL = 100 means the engine will fail in 100 cycles)</p><pre>train[&#39;RUL&#39;] = train.groupby(&#39;unit_id&#39;)[&#39;time_cycles&#39;].transform(lambda x: x.max() - x)</pre><p>RUL Calculation: For each engine, we find the last cycle it ran (x.max()), that’s when it failed, then subtract the current cycle from that to get the RUL at each point in time.</p><p>Let’s visualize this: So if Engine #1 failed at cycle 192</p><ul><li>At cycle 100: RUL = 192–100 = 92 cycles left</li><li>At cycle 191: RUL = 192–191 = 1 cycle left (about to fail)</li><li>At cycle 192: RUL = 0 (failed…..50k gone)</li></ul><p>Why <em>groupby</em>? Because we have 100 different engines in the training set, and each one has its own failure point. Without groupby, we’d mix up engines and get wrong RUL values.</p><h3>Step 2: Preprocessing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KASEONd4ouUGcIfi3sXDwg.png" /><figcaption>Figure: Sensor Behavior Across Engine Lifecycles</figcaption></figure><p>First, let’s check if all 21 sensors are useful by checking if all of them change throughout an engine’s lifetime. If the variance of the measurements for a sensor is &lt; 0.01, then we know that it’s not tracking degradation but rather just adding noise for our use case, so we can drop it.</p><pre># Drop constant sensors (variance &lt; 0.01)<br>sensor_cols = [c for c in columns if &#39;sensor&#39; in c]<br>variances = train[sensor_cols].var()<br>drop_sensors = variances[variances &lt; 0.01].index.tolist()<br>print(f&quot;Dropping {len(drop_sensors)} constant sensors: {drop_sensors}&quot;)</pre><p>Why does this matter? <a href="https://www.youtube.com/watch?v=YCzL96nL7j0">LSTMs </a>(the model we choose, more on that later) can get distracted by useless features. If a sensor reads “23.4” for 200 cycles straight, it’s not telling us anything about when the engine will fail.</p><pre># Normalize features (0–1)<br>scaler = MinMaxScaler()<br>train[feature_cols] = scaler.fit_transform(train[feature_cols])<br>test[feature_cols] = scaler.transform(test[feature_cols])</pre><p>Sensors measure completely different things, so they have different scales, for example:</p><ul><li>Temperature: 500–650°R</li><li>Pressure: 2–50 psia</li><li>Fan speed: 2000–2500 rpm</li></ul><p>That’s why we need normalization; without it, the LSTM would think fan speed (big numbers) is more important than pressure (small numbers), which is not true. MinMaxScaler squashes everything to the 0–1 range so the model treats all sensors equally.</p><p>FYI: We fit_transform on training data, then just transform on test data using the same scaler. This prevents data leakage, the test set doesn’t influence the scaling parameters.</p><pre># Create sequences for LSTM (window size = 30 cycles)<br>SEQUENCE_LENGTH = 30<br><br>def create_sequences(df, seq_len):<br>    sequences = []<br>    targets = []<br><br>    for unit_id in df[&#39;unit_id&#39;].unique():<br>        engine_data = df[df[&#39;unit_id&#39;] == unit_id]<br>        features = engine_data[feature_cols].values<br>        rul_values = engine_data[&#39;RUL&#39;].values<br><br>        for i in range(len(features) - seq_len + 1):<br>            sequences.append(features[i:i+seq_len])<br>            targets.append(rul_values[i+seq_len-1])<br><br>    return np.array(sequences), np.array(targets)</pre><p><strong>LSTMs don’t predict from single snapshots, they need to see trends over time</strong>. So we create sliding windows of 30 cycles.</p><p>Example for Engine #1:</p><ul><li>Cycles 1–30: predict RUL at cycle 30</li><li>Cycles 2–31: predict RUL at cycle 31</li><li>… and so on</li></ul><p>Each window is a 3D tensor: (30 timesteps, 17 features). The LSTM sees how temperature rises, vibration increases, and efficiency drops over those 30 cycles, then predicts remaining life.</p><p>Why 30 cycles? Trial and error from past experiments and literature. Too short (10 cycles) and the model can’t detect degradation trends. Too long (100 cycles) and you lose training samples.</p><pre># For test data, use last sequence of each engine<br>X_test = []<br>y_test = rul_test[&#39;RUL&#39;].values<br><br>for unit_id in test[&#39;unit_id&#39;].unique():<br>    engine_data = test[test[&#39;unit_id&#39;] == unit_id]<br>    features = engine_data[feature_cols].values<br><br>    # Pad if less than sequence length<br>    if len(features) &lt; SEQUENCE_LENGTH:<br>        pad = np.zeros((SEQUENCE_LENGTH - len(features), len(feature_cols)))<br>        features = np.vstack([pad, features])<br><br>    X_test.append(features[-SEQUENCE_LENGTH:])</pre><p>Test set handling is different. We only get one prediction per engine (the last 30 cycles we observed), because it’s similar to real-world deployment when you’re monitoring an engine in light, and at some point you need to say “this engine has X cycles left.”</p><p>The padding logic handles edge cases where a test engine has less than 30 cycles of data (rare but possible). We pad with zeros at the beginning, so the LSTM still gets a 30-cycle window.</p><pre>Dropping 10 constant sensors: [&#39;sensor_1&#39;, &#39;sensor_5&#39;, &#39;sensor_6&#39;, &#39;sensor_8&#39;, &#39;sensor_10&#39;, &#39;sensor_13&#39;, &#39;sensor_15&#39;, &#39;sensor_16&#39;, &#39;sensor_18&#39;, &#39;sensor_19&#39;]<br>Using 14 features<br>Saved: processed/scaler.pkl<br><br>Creating sequences (window=30)...<br>Train: (17731, 30, 14), (17731,)<br>Test: (100, 30, 14), (100,)<br><br>Saved to processed/:<br>  X_train.npy (17731, 30, 14)<br>  y_train.npy (17731,)<br>  X_test.npy (100, 30, 14)<br>  y_test.npy (100,)</pre><p>Out of 21 sensors, 10 were flatliners, they read nearly constant values throughout engine life. We kept:</p><ul><li>3 operational settings (altitude/Mach/throttle context)</li><li>11 varying sensors (the ones that actually change as engines degrade)</li></ul><p>Final dataset shape:</p><ul><li>Train: (17,731, 30, 14): 17,731 sequences, 30 timesteps each, 14 features</li><li>Test: (100, 30, 14): 100 engines, last 30 cycles, 14 features</li></ul><p>Basically each training sequence is a 30-cycle sliding window showing how those 14 features evolve over time and the LSTM model learns (hopefully) to recognize degradation patterns from these windows and predict RUL.</p><h3>Step 3: Training</h3><h3>Why LSTM (Long Short-Term Memory)?</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYCzL96nL7j0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYCzL96nL7j0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYCzL96nL7j0%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c6342816932729f8c3157543fe4bbdd/href">https://medium.com/media/8c6342816932729f8c3157543fe4bbdd/href</a></iframe><p>LSTM wins because it’s designed for exactly this problem: remembering long-term patterns in sequential data. When efficiency started dropping 20 cycles ago, LSTM keeps that context, also when vibration spiked briefly then normalized, it learns whether that matters or not.</p><p>The original NASA C-MAPSS paper used LSTMs, the USAF’s PANDA system (which cut B-1 bomber maintenance) uses LSTM-based architectures, and pretty much every RUL prediction benchmark uses it as the baseline. Plus, LSTMs train fast enough on CPUs (~5 minutes for this dataset) and don’t need the massive compute power.</p><p>I considered Random Forests (fast but no time awareness, you’d have to manually engineer features like “average temp over last 10 cycles”), simple RNNs (handle sequences but suffer from vanishing gradients, they forget early warning signs after 30+ timesteps).</p><p>If LSTM’s are good enough for the United States Air Force they are good enough for this project :)</p><pre># Build LSTM model<br>model = keras.Sequential([<br>    layers.LSTM(64, input_shape=(X_train.shape[1], X_train.shape[2]), return_sequences=True),<br>    layers.Dropout(0.2),<br>    layers.LSTM(32, return_sequences=False),<br>    layers.Dropout(0.2),<br>    layers.Dense(16, activation=&#39;relu&#39;),<br>    layers.Dense(1)<br>])<br><br>model.compile(optimizer=&#39;adam&#39;, loss=&#39;mse&#39;, metrics=[&#39;mae&#39;])<br>model.summary()</pre><p>The architecture is quite simple: two stacked LSTM layers with dropout between them.</p><p><strong>First LSTM layer (64 units):</strong></p><ul><li>Takes in sequences of shape (30 timesteps, 14 features)</li><li><em>return_sequences</em>=True means it outputs hidden states for every timestep, not just the last one giving the second LSTM layer the full temporal context to work with.</li></ul><p><strong>Dropout (20%):</strong> Randomly drops 20% of connections during training to prevent overfitting. LSTMs like any other RNN (recurrent neural network) are prone to memorizing patterns, especially with only 100 training engines.</p><p><strong>Second LSTM layer (32 units): </strong>Takes the first layer’s 64-dimensional sequence and compresses it further. By this point, the model has distilled 30 cycles of sensor data into a 32-number summary of engine health.</p><p><strong>Dense layers (16 to 1):</strong></p><ul><li>A small feedforward network that converts the LSTM’s output into a single RUL prediction</li><li>ReLU activation on the 16-unit layer adds non-linearity</li><li>Final layer has no activation (linear output) since RUL can be any positive number. no need to artificially constrain the output range when the model should freely predict anywhere from 0 to 200+ cycles.</li></ul><p><strong>Why MSE loss?</strong><br>Mean Squared Error penalizes large errors heavily. If the model predicts RUL=100 but the actual is RUL=10, that’s a big mistake (missed failure), and MSE makes sure the model learns to avoid it.</p><h3>Training Configuration</h3><pre>history = model.fit(<br>    X_train, y_train,<br>    validation_split=0.2,<br>    epochs=50,<br>    batch_size=128,<br>    verbose=1<br>)</pre><p><strong>Validation split:</strong> Hold out 20% of training data to monitor overfitting. If validation loss diverges from training loss, we’re memorizing instead of learning.</p><p><strong>50 epochs:</strong> Enough for the model to converge without overtraining. The C-MAPSS dataset is small enough that you can train the full model in ~5 minutes on a CPU.</p><p><strong>Batch size:</strong> Process 128 sequences at a time. Larger batches = faster training but less fine-grained gradient updates. 128 should be good for this dataset size.</p><p><strong>Adam optimizer:</strong> The default choice for deep learning. Automatically adjusts learning rates per-parameter.</p><h3>Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7IVKlMFrxM6UilmhBAFLCw.png" /><figcaption>Figure: Model Training and Prediction Performance</figcaption></figure><p><em>Train RMSE: 18.73 cycles<br>Test RMSE: 25.6 cycles</em></p><p><strong>What does RMSE = 25.6 cycles mean?</strong><br>On average, the model’s predictions are off by ~26 cycles. For engines with lifespans of 150–200 cycles, that’s roughly 13% error, good enough to schedule maintenance windows weeks in advance without too many false alarms.</p><p>The training curves (left plot) show clean convergence with mild oscillation after epoch 20, no severe overfitting, but some capacity remains underutilized or noisy.</p><p>The scatter plot (right) shows predictions clustering near the diagonal, with a slight conservative bias: <strong>the model tends to underestimate RUL at high values and overestimate at low values.</strong></p><p><strong>Why is this bias actually good?</strong><br>Underestimating high RUL means scheduling maintenance slightly early (inconvenient but safe).</p><p>Overestimating low RUL is also conservative, we’re more likely to catch<br>failures before they happen. For military aircraft, this is exactly the behavior you want: better to ground a jet unnecessarily than to have it fail mid-mission.</p><h3>Step 4: Dashboard</h3><p>Training a model is one thing, but making it useful for actual maintainers means building an interface they can use. I built a Dash dashboard that gives a real-time view of fleet health.</p><p>I chose <a href="https://dash.plotly.com/">Plotly Dash</a> over alternatives like Streamlit or Flask because it’s specifically designed for industrial dashboards, the kind of thing you’d deploy in a maintenance hangar. It handles real-time updates cleanly, the visualizations are interactive (hover to see details, zoom in/out), and it’s production-ready without extra configuration.</p><pre># Calculate risk levels<br>def get_risk_status(rul):<br>    if rul &lt; 30:<br>        return &#39;CRITICAL&#39;, &#39;red&#39;<br>    elif rul &lt; 80:<br>        return &#39;WARNING&#39;, &#39;orange&#39;<br>    else:<br>        return &#39;HEALTHY&#39;, &#39;green&#39;</pre><p>The three-tier system mirrors real maintenance protocols:</p><ul><li>CRITICAL (&lt; 30 cycles): Ground the aircraft immediately, schedule emergency maintenance.</li><li>WARNING (30–80 cycles): Plan maintenance within the next mission cycle.</li><li>HEALTHY (&gt; 80 cycles): Continue normal operations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Pu2EyYHKnNMSSZLQwO3Mw.png" /><figcaption>Figure: Predictive Maintenance Dashboard for Engine Fleet Monitoring</figcaption></figure><p>This color-coded system makes it instantly obvious which engines need attention, without requiring maintainers to interpret raw RUL numbers.</p><h3>Step 5: Cost Analysis</h3><p>Building an accurate model is pointless if you can’t prove it saves money. So I built a cost analysis comparing traditional maintenance vs AI-driven predictions.</p><pre>UNSCHEDULED_MAINTENANCE_COST = 50000 # Emergency repair<br>SCHEDULED_MAINTENANCE_COST = 10000 # Planned maintenance<br>TRADITIONAL_INTERVAL = 150 # Service every 150 cycles<br>INSPECTION_WINDOW = 30 # Catch issues 30 cycles out</pre><p>These numbers come from <a href="https://www.war.gov/">DoD </a>and online estimates. Unscheduled maintenance (emergency repairs after failure) costs 5x more than planned maintenance because you’re probably scrambling for parts, grounding aircraft unexpectedly, and disrupting mission schedules.</p><p><strong>Traditional Maintenance Logic</strong></p><p>Fixed-interval approach: service all engines at 150-cycle intervals, regardless of actual condition.</p><pre>def calculate_traditional_costs(actual_rul_list):<br>    total_cost = 0<br>    unscheduled = 0<br>    scheduled = 0<br><br>    for actual_rul in actual_rul_list:<br>        if actual_rul &lt; INSPECTION_WINDOW:<br>            # RUL too low - fails before next scheduled inspection<br>            total_cost += UNSCHEDULED_MAINTENANCE_COST<br>            unscheduled += 1<br>        else:<br>            # Caught by scheduled inspection (may be premature)<br>            total_cost += SCHEDULED_MAINTENANCE_COST<br>            scheduled += 1<br><br>    return total_cost, scheduled, unscheduled</pre><p>The problem: Engines with RUL &lt; 30 cycles slip through and fail unexpectedly. Engines with RUL &gt; 150 cycles get serviced too early, wasting resources.</p><p>Result for 100 engines:</p><ul><li>75 scheduled maintenance events</li><li>25 unscheduled failures (missed before inspection)</li><li>Total cost: $2,000,000</li><li>Fleet availability: 75%</li></ul><p><strong>Predictive Maintenance Logic</strong></p><p>AI-driven approach: use model predictions to schedule maintenance only when RUL &lt; 50 cycles.</p><pre>def calculate_predictive_costs(actual_rul_list, predicted_rul_list, threshold=50):<br>    total_cost = 0<br>    scheduled = 0<br>    unscheduled = 0<br><br>    for actual, predicted in zip(actual_rul_list, predicted_rul_list):<br>        if predicted &lt; threshold:<br>            # AI recommends maintenance<br>            # Schedule it regardless (model triggered action)<br>            total_cost += SCHEDULED_MAINTENANCE_COST<br>            scheduled += 1<br>        else:<br>            # AI says engine is healthy - no maintenance scheduled<br>            if actual &lt; threshold:<br>                # FALSE NEGATIVE: Missed a failing engine = emergency failure<br>                total_cost += UNSCHEDULED_MAINTENANCE_COST<br>                unscheduled += 1<br>            # else: TRUE NEGATIVE - correctly identified as healthy, no cost<br><br>    return total_cost, scheduled, unscheduled</pre><p>The advantage: Only service engines that actually need it. Catch failures early while avoiding unnecessary maintenance.</p><p>Result for 100 engines:</p><ul><li>34 scheduled maintenance events</li><li>0 unscheduled failures (model caught everything)</li><li>Total cost: $340,000</li><li>Fleet availability: 100%</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yb8G6qpf-ZPMzJU9RruAQA.png" /><figcaption>Figure: Economic and Operational Impact of Predictive Maintenance</figcaption></figure><p><strong>The Bottom Line</strong></p><p><em>Savings: $1,660,000 (83% reduction)</em></p><p>For a 100-engine fleet, AI-driven maintenance saves over $1.6M annually while keeping every aircraft mission-ready. Scale that to the USAF’s thousands of engines, and you’re talking tens of millions in savings.</p><p><strong>Why zero unscheduled failures?</strong><br>The model’s conservative bias (remember that RMSE = 25.6 with slight underestimation at high RUL) means it errs on the side of caution. At the 50-cycle threshold, it caught every engine that actually had RUL &lt; 50. No false negatives = no surprise failures.</p><p>Fleet availability matters for defense:</p><ul><li>Traditional maintenance: 25 engines grounded = 75% readiness</li><li>Predictive maintenance: 0 surprise failures = 100% readiness</li></ul><p>For military operations where you need maximum readiness that 25-percentage-point improvement is mission-critical.</p><p>Done! Saved a lot of money and the jets can keep flying with no problems :)</p><h3>References</h3><p>[1]: A. Saxena, K. Goebel, D. Simon and N. Eklund, “Damage propagation modeling for aircraft engine run-to-failure simulation,” <em>2008 International Conference on Prognostics and Health Management</em>, Denver, CO, USA, 2008, pp. 1–9, doi: 10.1109/PHM.2008.4711414.</p><p>[2]: Huiskens, M. (2024, June 10). <em>Air Force selects AI-Enabled predictive maintenance program as system of record</em>. C3 AI. <a href="https://c3.ai/air-force-selects-ai-enabled-predictive-maintenance-program-as-system-of-record/">https://c3.ai/air-force-selects-ai-enabled-predictive-maintenance-program-as-system-of-record/</a></p><p>[3]: Mihai Timoficiuc. (2025, October 11). <em>GitHub — MTimo27/jet-engines-predictive-maintenance</em>. GitHub. <a href="https://github.com/MTimo27/jet-engines-predictive-maintenance">https://github.com/MTimo27/jet-engines-predictive-maintenance</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85b9513ea9ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI Fashion Stylist with the Polyvore Dataset and CLIP Embeddings]]></title>
            <link>https://medium.com/@mihaitimoficiuc/building-an-ai-fashion-stylist-with-the-polyvore-dataset-and-clip-embeddings-d235a1cf7560?source=rss-2574d7bfbf34------2</link>
            <guid isPermaLink="false">https://medium.com/p/d235a1cf7560</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[fashion]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[polyvore]]></category>
            <dc:creator><![CDATA[Mihai Timoficiuc]]></dc:creator>
            <pubDate>Thu, 25 Sep 2025 19:21:12 GMT</pubDate>
            <atom:updated>2025-09-25T19:33:19.881Z</atom:updated>
            <content:encoded><![CDATA[<p>I was reading <a href="https://corporate.zalando.com/en/technology/inspiring-and-empowering-customers-ai-powered-experiences">this piece from Zalando</a> <a href="https://corporate.zalando.com/en/technology/inspiring-and-empowering-customers-ai-powered-experiences">(Inspiring and empowering customers with AI-powered experiences)</a> and thought, <em>hmmm</em>, that’s actually super cool.</p><p>It got me wondering: how does an e-commerce giant know what to recommend next to a customer? Sure, they’ve got the advantage of massive amounts of internal data, clicks, searches, purchases…basically endless datapoints (the dream for any Data Scientist or nightmare, it depends).</p><p>But what if you don’t have that kind of data? What if you’re dealing with millions of products, or worse, brand-new ones that nobody has interacted with yet?</p><p>That got me thinking, what if instead of relying on transaction data (“you bought this, so you might like that”), what if we could teach AI to understand visual compatibility directly from clothing images? (I was not the first one to ask that question, see the Appendix)</p><p>Zalando’s approach is interesting because they’re moving beyond pure transactions to something more inspirational and discovery-driven. Tools like Trend Spotter surface emerging fashion trends using signals like searches and likes, while the Assistant gives customers a conversational way to discover complete outfits.</p><p>Our project takes a different angle: using the Polyvore dataset of human-curated outfits, we can train a model to recognize which items naturally belong together. By extracting visual embeddings with CLIP and learning from thousands of real outfit combinations, we’re building an “AI stylist” that scores compatibility between any two clothing items.</p><p>Let’s see how AI can recommend what goes together! As always, the link to the repo is <a href="https://github.com/MTimo27/ai-fashion-stylist">here</a>.</p><h3><strong>First step: </strong>Like any other AI project, it involves getting the data</h3><p>I chose the <a href="https://huggingface.co/datasets/Marqo/polyvore"><strong>Polyvore 21K dataset</strong></a>, which contains around 21,000 outfits curated by real users of the <a href="https://en.wikipedia.org/wiki/Polyvore">Polyvore</a> platform. Unlike synthetic or automatically generated outfit combinations, every outfit on Polyvore was put together by humans who (hopefully) intuitively understand concepts such as color coordination, style, and compatibility. I assume users who make outfits on a specialized app know what they’re doing :)</p><p>This makes the dataset quite valuable because the <strong>ground truth reflects real human taste</strong>, which is very important when training a compatibility model. The dataset was curated and introduced by <em>Han et al.</em> in their ACM Multimedia paper <em>“</em><a href="https://arxiv.org/abs/1707.05691"><em>Learning Fashion Compatibility with Bidirectional LSTMs</em></a><em>”</em> (2017).</p><p>It’s worth noting that Polyvore itself was shut down in <strong>2018</strong>, so the outfits reflect fashion trends from that era, something to keep in mind when interpreting the model’s results.</p><pre>from datasets import load_dataset<br>import os<br><br>def download_polyvore_dataset():<br>    os.makedirs(&quot;data/raw&quot;, exist_ok=True)<br><br>    # Download dataset<br>    dataset = load_dataset(&quot;Marqo/polyvore&quot;)<br>    dataset.save_to_disk(&quot;data/raw/polyvore&quot;)<br><br>    print(&quot;Dataset downloaded successfully to data/raw/polyvore&quot;)<br>    print(&quot;Dataset splits:&quot;, list(dataset.keys()))<br><br>    # Basic info about the dataset<br>    data_split = dataset[&#39;data&#39;] <br>    print(f&quot;Total samples: {len(data_split)}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    download_polyvore_dataset()</pre><p>I’m using the <a href="https://huggingface.co/datasets/Marqo/polyvore">Polyvore dataset hosted on Hugging Face by Marqo</a>, a company doing some really cool work in this space.</p><p>Data format:</p><ul><li>image: PIL Image objects</li><li>category: string categories (Day Dresses, Boots, Handbags, Sunglasses)</li><li>text: descriptive text</li><li>item_ID: string IDs</li></ul><p>Let’s now analyze our dataset to see what’s actually inside:</p><pre>from datasets import load_from_disk<br>import json<br>from collections import Counter<br><br>def analyze_dataset():<br>    dataset = load_from_disk(&quot;data/raw/polyvore&quot;)<br>    data = dataset[&#39;data&#39;]<br><br>    print(f&quot;Items: {len(data)}&quot;)<br><br>    # Category distribution<br>    categories = Counter(item[&#39;category&#39;] for item in data)<br>    print(f&quot;\nAll categories ({len(categories)} total):&quot;)<br>    for category, count in categories.most_common():<br>        print(f&quot;  {category}: {count}&quot;)<br><br>    with open(&quot;data/processed/train_pairs.json&quot;, &quot;r&quot;) as f:<br>        train_pairs = json.load(f)<br>    print(f&quot;\nTraining pairs: {len(train_pairs)}&quot;)<br><br>    # Positive pair combinations<br>    positive_combos = Counter()<br>    for idx1, idx2, label in train_pairs:<br>        if label == 1:<br>            cat1 = data[idx1][&#39;category&#39;]<br>            cat2 = data[idx2][&#39;category&#39;]<br>            combo = tuple(sorted([cat1, cat2]))<br>            positive_combos[combo] += 1<br><br>    print(f&quot;\nTop compatible pairs:&quot;)<br>    for combo, count in positive_combos.most_common(10):<br>        print(f&quot;  {combo[0]} + {combo[1]}: {count}&quot;)<br><br>    # Find category pairs that never appear together<br>    all_categories = set(item[&#39;category&#39;] for item in data)<br>    never_paired = []<br><br>    for cat1 in sorted(all_categories):<br>        for cat2 in sorted(all_categories):<br>            if cat1 &lt; cat2:<br>                combo = (cat1, cat2)<br>                if combo not in positive_combos:<br>                    never_paired.append(combo)<br><br>    print(f&quot;\nNever paired together ({len(never_paired)} total):&quot;)<br>    for combo in never_paired[:15]:<br>        print(f&quot;  {combo[0]} + {combo[1]}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    analyze_dataset()</pre><pre>#Output shrunk for the purpose of the article:<br><br>Items: 94096<br>Training pairs: 192536<br><br>Top categories:<br>  Earrings: 3606<br>  Shoulder Bags: 3525<br>  Necklaces: 3379<br>  Tops: 2851<br>  Sandals: 2689<br>  Day Dresses: 2525<br>  Bracelets &amp; Bangles: 2505<br>  Pumps: 2422<br>  Clutches: 2377<br>  Ankle Booties: 2355<br><br>Top compatible pairs:<br>  Bracelets &amp; Bangles + Earrings: 671<br>  Earrings + Necklaces: 617<br>  Earrings + Rings: 555<br>  Earrings + Shoulder Bags: 532<br>  Clutches + Earrings: 499<br>  Necklaces + Shoulder Bags: 473<br>  Earrings + Sandals: 471<br>  Earrings + Pumps: 456<br>  Day Dresses + Shoulder Bags: 447<br>  Bracelets &amp; Bangles + Necklaces: 440</pre><h3>Second Step: Pair clothes into outfits based on their ID</h3><pre>from datasets import load_from_disk<br>import random<br>import json<br>import os<br>from collections import defaultdict<br>import itertools<br><br>def create_compatibility_pairs():<br>    dataset = load_from_disk(&quot;data/raw/polyvore&quot;)<br>    data = dataset[&#39;data&#39;]<br><br>    print(f&quot;Total items: {len(data)}&quot;)<br><br>    # Group items by potential outfit ID (first part of item_ID)<br>    outfit_groups = defaultdict(list)<br>    for i, item in enumerate(data):<br>        # Extract potential outfit ID from item_ID<br>        outfit_id = item[&#39;item_ID&#39;].split(&#39;_&#39;)[0]<br>        outfit_groups[outfit_id].append(i)<br><br>    # Filter to outfits with 2+ items<br>    valid_outfits = {k: v for k, v in outfit_groups.items() if len(v) &gt;= 2}<br>    print(f&quot;Found {len(valid_outfits)} outfits with 2+ items&quot;)<br><br>    # Create positive pairs (items from same outfit)<br>    positive_pairs = []<br>    for outfit_id, item_indices in valid_outfits.items():<br>        # Create all combinations of items in this outfit<br>        for i, j in itertools.combinations(item_indices, 2):<br>            positive_pairs.append((i, j, 1))  # 1 = compatible<br><br>    print(f&quot;Created {len(positive_pairs)} positive pairs&quot;)<br><br>    # Create negative pairs (items from different outfits)<br>    negative_pairs = []<br>    outfit_items = list(valid_outfits.values())<br><br>    # Create more negatives (3x positives for better balance)<br>    target_negatives = len(positive_pairs) * 3<br><br>    for _ in range(target_negatives):<br>        # Pick two different outfits<br>        outfit1, outfit2 = random.sample(outfit_items, 2)<br>        # Pick random item from each<br>        item1 = random.choice(outfit1)<br>        item2 = random.choice(outfit2)<br>        negative_pairs.append((item1, item2, 0))  # 0 = incompatible<br><br>    print(f&quot;Created {len(negative_pairs)} negative pairs&quot;)<br><br>    # Combine and shuffle<br>    all_pairs = positive_pairs + negative_pairs<br>    random.shuffle(all_pairs)<br><br>    # Split into train/val<br>    split_idx = int(0.8 * len(all_pairs))<br>    train_pairs = all_pairs[:split_idx]<br>    val_pairs = all_pairs[split_idx:]<br><br>    # Save pairs<br>    os.makedirs(&quot;data/processed&quot;, exist_ok=True)<br><br>    with open(&quot;data/processed/train_pairs.json&quot;, &quot;w&quot;) as f:<br>        json.dump(train_pairs, f)<br><br>    with open(&quot;data/processed/val_pairs.json&quot;, &quot;w&quot;) as f:<br>        json.dump(val_pairs, f)<br><br>    print(f&quot;Train pairs: {len(train_pairs)} (pos: {sum(1 for p in train_pairs if p[2] == 1)})&quot;)<br>    print(f&quot;Val pairs: {len(val_pairs)} (pos: {sum(1 for p in val_pairs if p[2] == 1)})&quot;)<br><br>    print(&quot;Pairs saved to data/processed/&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    random.seed(42)<br>    create_compatibility_pairs()</pre><ol><li>Loaded the Polyvore dataset with fashion items grouped into outfits.</li><li>Grouped items by outfit ID ([outfit-nr]_[item-nr] -&gt; split on _) and filtered out single-item outfits (a lone T-shirt doesn’t teach much about style).</li><li>Used itertools.combinations to generate all possible item pairs within each outfit -&gt; these are our compatible pairs.</li><li>For incompatible pairs, I initially tried manually defining bad category combinations (sneakers + gowns, winter coats + bikinis), but surprisingly, this performed worse than a simpler random approach. So I went back to basics: picked items from completely different outfits and paired them up. The logic? If an experienced user curated outfit A and outfit B separately, randomly mixing items between them is likely to create mismatched combinations.</li><li>Created 3x more negative pairs than positive ones (75% incompatible, 25% compatible) to teach the model to be <strong>appropriately selective</strong>, just like real fashion where most random combinations don’t work. <em>Fashion retailers like Zalando use negative-heavy ratios because a bad recommendation (customer buys mismatched items and returns them) costs more than a missed opportunity (not showing a good combo).</em></li><li>Labeled compatible pairs as (1) and incompatible as pairs (0).</li><li>Combined all pairs, shuffled them, and split into an 80/20 train/validation set.</li></ol><p>Saved everything neatly into JSON files for model training. Done!</p><pre>Total items: 94096<br>Found 20614 outfits with 2+ items<br>Created 190670 positive pairs<br>Created 572010 negative pairs<br>Train pairs: 610144 (pos: 152390)<br>Val pairs: 152536 (pos: 38280)<br>Pairs saved to data/processed/</pre><h3>Third Step: Turn images into numerical representations</h3><pre>from datasets import load_from_disk<br>import torch<br>import numpy as np<br>from transformers import CLIPProcessor, CLIPModel<br>import os<br>from tqdm import tqdm<br><br>def extract_clip_features():<br>    model = CLIPModel.from_pretrained(&quot;openai/clip-vit-base-patch32&quot;)<br>    processor = CLIPProcessor.from_pretrained(&quot;openai/clip-vit-base-patch32&quot;, use_fast=False)<br><br>    # Move to GPU if available<br>    device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>    model = model.to(device)<br>    print(f&quot;Using device: {device}&quot;)<br><br>    dataset = load_from_disk(&quot;data/raw/polyvore&quot;)<br>    data = dataset[&#39;data&#39;]<br><br>    print(f&quot;Extracting image and text features for {len(data)} items...&quot;)<br><br>    # Extract features in batches<br>    batch_size = 16<br>    all_image_features = []<br>    all_text_features = []<br><br>    for i in tqdm(range(0, len(data), batch_size), desc=&quot;Extracting features&quot;):<br>        batch_end = min(i + batch_size, len(data))<br><br>        # Get images and texts for this batch<br>        batch_images = [data[j][&#39;image&#39;] for j in range(i, batch_end)]<br>        batch_texts = [data[j][&#39;text&#39;] for j in range(i, batch_end)]<br><br>        # Process images and texts<br>        image_inputs = processor(images=batch_images, return_tensors=&quot;pt&quot;, padding=True)<br>        text_inputs = processor(text=batch_texts, return_tensors=&quot;pt&quot;, padding=True, truncation=True)<br><br>        # Move to device<br>        image_inputs = {k: v.to(device) for k, v in image_inputs.items()}<br>        text_inputs = {k: v.to(device) for k, v in text_inputs.items()}<br><br>        # Extract features<br>        with torch.no_grad():<br>            # Extract image features<br>            image_features = model.get_image_features(**image_inputs)<br>            image_features = image_features / image_features.norm(dim=-1, keepdim=True)<br><br>            # Extract text features<br>            text_features = model.get_text_features(**text_inputs)<br>            text_features = text_features / text_features.norm(dim=-1, keepdim=True)<br><br>        all_image_features.append(image_features.cpu().numpy())<br>        all_text_features.append(text_features.cpu().numpy())<br><br>    # Combine all features<br>    image_features = np.vstack(all_image_features)<br>    text_features = np.vstack(all_text_features)<br><br>    # Concatenate image and text features<br>    combined_features = np.concatenate([image_features, text_features], axis=1)<br><br>    print(f&quot;Image features shape: {image_features.shape}&quot;)<br>    print(f&quot;Text features shape: {text_features.shape}&quot;)<br>    print(f&quot;Combined features shape: {combined_features.shape}&quot;)<br><br>    # Save features<br>    os.makedirs(&quot;data/processed&quot;, exist_ok=True)<br>    np.save(&quot;data/processed/improved_clip_features.npy&quot;, combined_features)<br><br>    print(&quot;Combined features saved to data/processed/improved_clip_features.npy&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    extract_clip_features()</pre><p><a href="https://openai.com/index/clip/">OpenAI’s CLIP model</a>: basically translating style into numbers the model can understand.</p><p>We use the <a href="https://huggingface.co/openai/clip-vit-base-patch32">clip-vit-base-patch32 </a>variant because it has: good feature quality, fast enough for batch processing, and not too memory-hungry. Compared to other vision models like ResNet or niche fashion models, CLIP is the clear winner: free, widely used, and already trained on massive visual datasets, making it the fit for a fashion compatibility pipeline.</p><p>Plus CLIP handles both images AND text descriptions from the Polyvore dataset. We extract 512-dimensional embeddings from each clothing item’s photo, plus another 512 dimensions from its text description (like “tibi knit long sleeve dress” or “michael kors leather over-the-knee boots”), then concatenate them into rich 1024-dimensional features that capture both visual style and semantic meaning.</p><p>Images are processed in batches of 16 (for performance reasons, as I don’t yet have access to a <a href="https://www.nvidia.com/en-us/data-center/a100/">A100 Tensor Core GPU</a>) and every embedding is normalized so the model compares direction (style similarity) rather than raw size. Finally, all features are saved in a .npy file instead of JSON, since it’s faster to load, keeps precision intact, and doesn’t waste space.</p><h3>Fourth Step: Create and train the model</h3><pre> model = keras.Sequential([<br>        layers.Input(shape=(input_dim,)),<br>        layers.Dense(512, activation=&#39;relu&#39;, kernel_regularizer=keras.regularizers.l2(0.001)),<br>        layers.BatchNormalization(),<br>        layers.Dropout(0.3),<br>        layers.Dense(256, activation=&#39;relu&#39;, kernel_regularizer=keras.regularizers.l2(0.001)),<br>        layers.BatchNormalization(),<br>        layers.Dropout(0.3),<br>        layers.Dense(128, activation=&#39;relu&#39;),<br>        layers.Dropout(0.2),<br>        layers.Dense(1, activation=&#39;sigmoid&#39;)<br>    ])<br>    model.compile(<br>        optimizer=keras.optimizers.Adam(learning_rate=0.0005),<br>        loss=&#39;binary_crossentropy&#39;,<br>        metrics=[&#39;accuracy&#39;, &#39;auc&#39;]<br>    )<br>    return model</pre><p>The compatibility model is a straightforward feedforward neural net, nothing too wow, but good enough to spot patterns in outfit pairings.</p><p>We feed it a 2048-dim vector (two CLIP embeddings stuck together), and then it squeezes that down layer by layer: first 512 neurons with ReLU, batch norm, and 30% dropout (helps prevent overfitting by randomly turning off some neurons during training), then 256 with the same setup, then 128 with lighter 20% dropout.</p><p>At the end, there’s a single sigmoid neuron that spits out a score between 0 and 1: basically, “<strong>do these two pieces go together or not?</strong>”</p><p>To keep it from overfitting, I added L2 regularization on the big layers, plus dropout throughout. Batch norm keeps training stable, and Adam with a small 0.0005 learning rate makes sure it converges without being too volatile….hopefully…. For training, we use binary cross-entropy loss, and we track both accuracy and AUC (basically a measure of how well the model separates positives from negatives across all possible thresholds), since AUC is better for imbalanced datasets.</p><pre> callbacks = [<br>      keras.callbacks.EarlyStopping(monitor=&#39;val_loss&#39;, patience=8, restore_best_weights=True, mode=&#39;min&#39;),<br>      keras.callbacks.ModelCheckpoint(&#39;models/improved_best_compatibility_model.keras&#39;, monitor=&#39;val_auc&#39;, save_best_only=True, mode=&#39;max&#39;),<br>      keras.callbacks.ReduceLROnPlateau(monitor=&#39;val_loss&#39;, factor=0.7, patience=4, min_lr=1e-6),<br>      keras.callbacks.LearningRateScheduler(lambda epoch: 0.0005 * 0.98**epoch)<br>  ]</pre><p>We added a few tricks to keep the model honest. Early stopping cuts training once validation stops improving, so we don’t overfit. Threshold optimization finds the best decision point using F1 instead of blindly sticking to 0.5. Class weighting fixes the 3:1 imbalance so the model doesn’t just predict “incompatible” all the time. And a learning rate schedule slowly lowers the rate each epoch for smoother convergence.</p><p>Quite a lot. I know. But how does it perform?</p><pre>{<br>  &quot;best_threshold&quot;: 0.5769704580307007,<br>  &quot;validation_accuracy&quot;: 0.7628100907326795,<br>  &quot;validation_auc&quot;: 0.856851725577438,<br>  &quot;feature_type&quot;: &quot;improved&quot;,<br>  &quot;input_dimension&quot;: 2048,<br>  &quot;model_parameters&quot;: 1216513<br>}<br><br>Classification Report:<br>              precision    recall  f1-score   support<br><br>           0       0.92      0.75      0.83    114256<br>           1       0.52      0.80      0.63     38280<br><br>    accuracy                           0.76    152536<br>   macro avg       0.72      0.77      0.73    152536<br>weighted avg       0.82      0.76      0.78    152536<br><br>Random examples (threshold=0.577):<br>Good Actual=1, Predicted=1, Prob=0.841<br>Good Actual=0, Predicted=0, Prob=0.029<br>Good Actual=0, Predicted=0, Prob=0.332<br>Good Actual=0, Predicted=0, Prob=0.052<br>Good Actual=1, Predicted=1, Prob=0.925</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pyDjcvUUODlEi0PEnAd8-g.png" /><figcaption>Model Accuracy and Model Loss</figcaption></figure><p>In this training run, both training and validation accuracy steadily improve and stay close to each other, with validation accuracy sometimes a bit higher but fluctuating more (which is normal since the validation set is smaller).</p><p>The losses also decrease together, and validation loss stays lower than training loss throughout, suggesting that the model is generalizing well and not overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGm7DqgfofjqDEt9BY0UYA.png" /><figcaption>Test 1</figcaption></figure><p>I also evaluated the model on unseen item pairs: for example, it correctly identified that a Minnie Mouse T-shirt and suit pants don’t go well together, while pairing the suit pants with a regular blue shirt produced a confident match.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N51vWbaXRXOVWMDLi0kbYw.png" /><figcaption>Test 2</figcaption></figure><p>To wrap it up, I really enjoyed working on this project. It was a bit messy at times, especially figuring out how to generate good negative pairs and tuning model parameters, but that trial-and-error is part of any ML project :) Is it perfect? No. Was it cool to build? Yes!</p><h3>Appendix: Here are the papers I found interesting:</h3><ul><li><a href="https://research.zalando.com/fashionxrecsys/workshop-files/fashionxrecsys2019_paper_8.pdf">Laenen, K., &amp; Moens, M.-F. (2019). <em>Attention-based fusion for outfit recommendation</em>. Department of Computer Science, KU Leuven.</a></li><li><a href="https://doi.org/10.1145/3292500.3330652">Chen, W., Huang, P., Xu, J., Guo, X., Guo, C., Sun, F., Li, C., Pfadler, A., Zhao, H., &amp; Zhao, B. (2019, August 4–8). POG: Personalized outfit generation for fashion recommendation at Alibaba iFashion. In Proceedings of the 25th ACM SIGKDD Conference on Knowledge Discovery and Data Mining (pp. 2662–2670). ACM.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d235a1cf7560" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Better Decisions than Ferrari: Building an AI Formula 1 Strategist]]></title>
            <link>https://medium.com/@mihaitimoficiuc/make-better-decisions-than-ferrari-building-an-ai-formula-1-strategist-238c3ab7d4d5?source=rss-2574d7bfbf34------2</link>
            <guid isPermaLink="false">https://medium.com/p/238c3ab7d4d5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[formula-1]]></category>
            <category><![CDATA[strategy]]></category>
            <category><![CDATA[random-forest-classifiers]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Mihai Timoficiuc]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 12:20:06 GMT</pubDate>
            <atom:updated>2025-09-11T12:20:06.162Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xavFXk50qRT2VVKLbaepBw.jpeg" /><figcaption><a href="https://www.planetf1.com/news/charles-leclerc-kimi-antonelli-dutch-gp-crash-too-much">https://www.planetf1.com/news/charles-leclerc-kimi-antonelli-dutch-gp-crash-too-much</a></figcaption></figure><p>After watching the latest Dutch GP and crying over both of my favorite drivers’ races going down the drain, this time mostly thanks to Kimi Antonelli and the rain, I started wondering how tough it would be to build an AI system that could handle race strategy decisions.</p><p>So why not try? Let’s build a Random Forest model that can actually learn and, well, even “speak” Italian (sort of).</p><h4>Project structure:</h4><p>You can find the complete project code <a href="https://github.com/MTimo27/f1-ai-strategist">here</a>.</p><pre>strategist/<br>  ├── README.md<br>  ├── requirements.txt<br>  ├── main.py                          # FastAPI application entry point<br>  ├── CLAUDE.md                        # Project instructions for Claude Code<br>  │<br>  ├── src/<br>  │   ├── __init__.py<br>  │   │<br>  │   ├── api/                         # FastAPI Layer<br>  │   │   ├── __init__.py<br>  │   │   ├── api.py                   # FastAPI routes &amp; endpoints<br>  │   │   └── entities.py              # Pydantic request/response models<br>  │   │<br>  │   ├── core/                        # Strategy Engine<br>  │   │   ├── __init__.py<br>  │   │   ├── strategy.py              # Main StrategyEngine class<br>  │   │   ├── strategy_config.py       # Strategy constants &amp; configuration<br>  │   │   ├── model.py                 # TireStrategyModel ML wrapper<br>  │   │   ├── train_model.py           # Model training script<br>  │   │   ├── data_processor.py        # F1DataProcessor for ML features<br>  │   │   └── model_performance_analysis.py  # Model evaluation &amp; visualization<br>  │   │<br>  │   ├── data/                        # Data Layer<br>  │   │   ├── __init__.py<br>  │   │   ├── database.py              # SQLAlchemy connection &amp; session<br>  │   │   ├── entities.py              # SQLAlchemy ORM models<br>  │   │   ├── fastf1_client.py         # FastF1 API integration<br>  │   │   └── fetch_data.py            # Data fetching utilities<br>  │   │<br>  │   └── ferrari_comparison/          # Analysis Tools<br>  │       ├── __init__.py<br>  │       └── ferrari_vs_model_comparison.py  # Ferrari vs AI analysis<br>  │<br>  ├── database/<br>  │   ├── race_data.db                 # SQLite database<br>  │   └── cache/                       # FastF1 cache directory<br>  │       └── [FastF1 cached files]<br>  │<br>  ├── models/<br>  │   └── tire_strategy_model.pkl      # Trained Random Forest model<br>  │<br>  └── outputs/                         # Generated Analysis<br>      ├── ferrari_vs_ai_comparison.png<br>      ├── race_strategy_disagreements.png<br>      ├── model_performance_analysis.png<br>      └── model_performance_metrics.json</pre><h4>First lets get our data:</h4><p>Before we can build any F1 AI strategist, we need quality data. After researching various options, I chose the <a href="https://medium.com/r?url=https%3A%2F%2Fgithub.com%2FtheOehrly%2FFast-F1">FastF1</a> Python package because:</p><ol><li>It has a clean well-documented API that abstracts a lot of the complexity of F1’s telemetry systems;</li><li>Access to detailed lap-by-lap data going back to 2018, including tire compounds, pit stops, weather conditions, and track status; Not just lap times, but strategic data like tire age, stint information, and position changes;</li><li>It’s free and open source :)</li></ol><p><strong>Database Choice: </strong><a href="https://sqlite.org/"><strong>SQLite</strong></a></p><p>I wanted something fast that didn’t need a server setup and had a single file database that is perfect for prototyping and development. Plus SQLite works seamlessly with the <a href="https://docs.sqlalchemy.org/en/20/orm/">SQLAlchemy ORM</a> (Object–Relational Mapper). You can browse the data visually using the <a href="https://github.com/sqlitebrowser/sqlitebrowser">sqlitebrowser </a>.</p><p>Data Pipeline Architecture</p><p>What Data Should We Capture? Let’s look at the straightforward RaceData class:</p><pre>from sqlalchemy import Column, Integer, String, Float, Boolean<br>from sqlalchemy.ext.declarative import declarative_base<br><br>Base = declarative_base()<br><br>class RaceData(Base):<br>    __tablename__ = &quot;race_data&quot;<br>    <br>    # Basic info<br>    id = Column(Integer, primary_key=True)<br>    year = Column(Integer, nullable=False)<br>    round = Column(Integer, nullable=False)<br>    race_name = Column(String)<br>    driver = Column(String, nullable=False)<br>    team = Column(String)<br>    lap = Column(Integer, nullable=False)<br><br>    # Performance info<br>    lap_time = Column(Float)<br>    compound = Column(String)<br>    stint = Column(Integer)<br>    <br>    # Strategy-relevant data<br>    tyre_age = Column(Integer)<br>    fresh_tyre = Column(Boolean)<br>    pit_stop_time = Column(Float)<br>    position = Column(Integer)<br>    track_status = Column(String)  # Green, Yellow, SC, VSC, Red<br><br>    # Context<br>    weather_condition = Column(String)<br>    air_temp = Column(Float)<br>    track_temp = Column(Float)<br>    <br>    # Ferrari-specific comparison data<br>    is_ferrari = Column(Boolean, default=False)</pre><p>The Database class in database.py handles all the database operations for the F1 Strategy Predictions API. It sets up a SQLite database at database/race_data.db, makes sure the folder exists, builds the SQLAlchemy engine and session maker, creates tables from the ORM models, and gives a handy get_session() method to run queries and transactions.</p><pre>from sqlalchemy import create_engine<br>from sqlalchemy.orm import sessionmaker<br>from .entities import Base<br>import os<br><br>class Database:<br>    def __init__(self):<br>        db_path = os.path.join(os.path.dirname(__file__), &quot;..&quot;, &quot;..&quot;, &quot;database&quot;, &quot;race_data.db&quot;)<br>        os.makedirs(os.path.dirname(db_path), exist_ok=True)<br>            <br>        self.engine = create_engine(f&quot;sqlite:///{db_path}&quot;)<br>        self.SessionLocal = sessionmaker(bind=self.engine)<br>        <br>    def create_tables(self):<br>        Base.metadata.create_all(bind=self.engine)<br>    <br>    def get_session(self):<br>        return self.SessionLocal()</pre><p>Now lets break down the FastF1Client class:</p><p>First we need to initialize the FastF1 client by setting up the cache path (we need to do this because FastF1 handles massive amounts of data — around 50–100MB per race session, and caching dramatically speeds up our scripts by storing this data locally instead of re-downloading it every time). We also initialize our database connection and data validator components that we’ll use later in the pipeline.</p><pre>class FastF1Client:<br>    def __init__(self):<br>        &quot;&quot;&quot;Initialize FastF1 client with database and validator&quot;&quot;&quot;<br>        # Setup FastF1 cache<br>        cache_path = os.path.join(os.path.dirname(__file__), &quot;..&quot;, &quot;..&quot;, &quot;database&quot;, &quot;cache&quot;)<br>        os.makedirs(cache_path, exist_ok=True)<br>        fastf1.Cache.enable_cache(cache_path)<br>        <br>        # Initialize components<br>        self.db = Database()<br>        self.validator = DataValidator()</pre><p>Now what does the fetch_and_save_all_data method do? (It’s in the name haha)</p><p>Step by step:</p><ol><li>Creates the database tables for RaceData.</li><li>Maps each year (2023–2025) to the number of races that season.</li><li><em>Note: calling fastf1.get_session(year, round_num, ‘R’) with a non-existent round (like Round 25 in 2023) throws an error.</em></li><li>Loops through each year and race, use get_session() to grab race data, then load() all telemetry.</li><li>For each driver, uses pick_drivers() to get lap data.</li><li>Extracts the team name and flags Ferrari for later strategy analysis.</li><li>Loops through laps and populates the RaceData entities with key info.</li><li>Validates everything with a custom check to make sure the data is clean. (the most important step)</li><li>Saves it to the database. Done!</li></ol><pre> def fetch_and_save_all_data(self):<br>        &quot;&quot;&quot;Fetch all F1 data from 2023-2025 seasons and save to database&quot;&quot;&quot;<br>        print(&quot;Starting F1 data collection...&quot;)<br>        <br>        # Initialize database<br>        self.db.create_tables()<br>        <br>        # Define seasons to fetch<br>        seasons = {<br>            2023: 23,  # 23 races<br>            2024: 24,  # 24 races  <br>            2025: 24   # 24 races<br>        }<br>        <br>        # Process each season<br>        for year, total_races in seasons.items():<br>            print(f&quot;\nFetching {year} season ({total_races} races)...&quot;)<br>            <br>            for round_num in range(1, total_races + 1):<br>                try:<br>                    print(f&quot;Processing {year} Round {round_num}...&quot;, end=&quot; &quot;)<br>                    <br>                    # Load race session<br>                    session = fastf1.get_session(year, round_num, &#39;R&#39;)<br>                    session.load()<br>                    <br>                    # Process all drivers in this race<br>                    race_data = []<br>                    for driver in session.drivers:<br>                        driver_laps = session.laps.pick_drivers(driver)<br>                        if driver_laps.empty:<br>                            continue<br>                        <br>                        # Get team info<br>                        team_name = str(driver_laps.iloc[0].get(&#39;Team&#39;, &#39;Unknown&#39;))<br>                        is_ferrari = &#39;FERRARI&#39; in team_name.upper()<br>                        <br>                        # Process each lap<br>                        for _, lap in driver_laps.iterrows():<br>                            if lap[&#39;LapTime&#39;] is not None:<br>                                lap_data = {<br>                                    &#39;year&#39;: year,<br>                                    &#39;round&#39;: round_num,<br>                                    &#39;race_name&#39;: session.event[&#39;EventName&#39;],<br>                                    &#39;driver&#39;: driver,<br>                                    &#39;team&#39;: team_name,<br>                                    &#39;lap&#39;: lap[&#39;LapNumber&#39;],<br>                                    &#39;lap_time&#39;: lap[&#39;LapTime&#39;].total_seconds(),<br>                                    &#39;compound&#39;: lap[&#39;Compound&#39;],<br>                                    &#39;stint&#39;: lap[&#39;Stint&#39;],<br>                                    &#39;tyre_age&#39;: int(lap.get(&#39;TyreLife&#39;, 0)) if pd.notna(lap.get(&#39;TyreLife&#39;)) else 0,<br>                                    &#39;fresh_tyre&#39;: int(lap.get(&#39;TyreLife&#39;, 0)) &lt;= 1 if pd.notna(lap.get(&#39;TyreLife&#39;)) else False,<br>                                    &#39;position&#39;: int(lap[&#39;Position&#39;]) if lap.get(&#39;Position&#39;) and lap[&#39;Position&#39;] &gt; 0 else None,<br>                                    &#39;track_status&#39;: str(lap.get(&#39;TrackStatus&#39;, &#39;Unknown&#39;)),<br>                                    &#39;is_ferrari&#39;: is_ferrari<br>                                }<br>                                race_data.append(lap_data)<br>                    <br>                    # Validate and save data<br>                    if race_data:<br>                        valid_data, validation_report = self.validator.validate_and_clean_race_data(race_data, year, round_num)<br>                        <br>                        # Save to database<br>                        with self.db.get_session() as db_session:<br>                            for data in valid_data:<br>                                race_record = RaceData(**data)<br>                                db_session.add(race_record)<br>                            db_session.commit()<br>                        <br>                        print(f&quot;Saved {len(valid_data)} records&quot;)<br>                    else:<br>                        print(&quot;No data found&quot;)<br>                        <br>                except Exception as e:<br>                    print(f&quot;Error: {e}&quot;)<br>                    continue</pre><p>The DataValidator is basically the quality control for all F1 race data before it hits the database. It makes sure key fields like year, round, driver, lap number, and lap time actually exist and make sense (think years 2020–2030, rounds 1–30, lap times positive). It also checks that tire compounds are legit (SOFT, MEDIUM, HARD, INTERMEDIATE, WET) and that driver positions don’t exceed the 22-car grid. For every race, it spits out a detailed report showing what passed and what didn’t, so we keep our data clean and know exactly where things went wrong while processing FastF1 data.</p><pre>from datetime import datetime<br><br><br>class DataValidator:<br>    def __init__(self):<br>        self.validation_reports = []<br>    <br>    def validate_and_clean_race_data(self, race_data, year=None, round_num=None):<br>        &quot;&quot;&quot;<br>        Validate F1 race data and return only valid records.<br>        <br>        Checks that each lap record has required fields and reasonable values,<br>        then returns cleaned data ready for database storage.<br>        &quot;&quot;&quot;<br>        if not race_data:<br>            return []<br>        <br>        valid_data = []<br>        errors = []<br>        <br>        # Valid tire compounds according to F1 regulations<br>        valid_compounds = [&#39;SOFT&#39;, &#39;MEDIUM&#39;, &#39;HARD&#39;, &#39;INTERMEDIATE&#39;, &#39;WET&#39;]<br>        <br>        for i, lap in enumerate(race_data):<br>            lap_errors = []<br>            <br>            # Check required fields exist<br>            required_fields = [&#39;year&#39;, &#39;round&#39;, &#39;driver&#39;, &#39;lap&#39;, &#39;lap_time&#39;]<br>            for field in required_fields:<br>                if field not in lap or lap[field] is None:<br>                    lap_errors.append(f&quot;Missing {field}&quot;)<br>            <br>            # Validate year is reasonable<br>            if &#39;year&#39; in lap and (lap[&#39;year&#39;] &lt; 2020 or lap[&#39;year&#39;] &gt; 2030):<br>                lap_errors.append(f&quot;Invalid year: {lap[&#39;year&#39;]}&quot;)<br>            <br>            # Validate round number<br>            if &#39;round&#39; in lap and (lap[&#39;round&#39;] &lt; 1 or lap[&#39;round&#39;] &gt; 30):<br>                lap_errors.append(f&quot;Invalid round: {lap[&#39;round&#39;]}&quot;)<br>            <br>            # Validate lap time is positive<br>            if &#39;lap_time&#39; in lap and lap[&#39;lap_time&#39;] and lap[&#39;lap_time&#39;] &lt;= 0:<br>                lap_errors.append(f&quot;Invalid lap time: {lap[&#39;lap_time&#39;]}&quot;)<br>            <br>            # Validate tire compound<br>            if &#39;compound&#39; in lap and lap[&#39;compound&#39;] and lap[&#39;compound&#39;] not in valid_compounds:<br>                lap_errors.append(f&quot;Invalid compound: {lap[&#39;compound&#39;]}&quot;)<br>            <br>            # Validate position is within F1 grid size<br>            if &#39;position&#39; in lap and lap[&#39;position&#39;] and (lap[&#39;position&#39;] &lt; 1 or lap[&#39;position&#39;] &gt; 22):<br>                lap_errors.append(f&quot;Invalid position: {lap[&#39;position&#39;]}&quot;)<br>            <br>            # If no errors, this lap is valid<br>            if not lap_errors:<br>                valid_data.append(lap)<br>            else:<br>                errors.extend([f&quot;Lap {i+1}: {error}&quot; for error in lap_errors])<br>        <br>        # Create validation report<br>        race_key = f&quot;{year}_{round_num}&quot; if year and round_num else &quot;unknown&quot;<br>        validation_report = {<br>            &quot;race&quot;: race_key,<br>            &quot;year&quot;: year,<br>            &quot;round&quot;: round_num,<br>            &quot;timestamp&quot;: datetime.now().isoformat(),<br>            &quot;total_records&quot;: len(race_data),<br>            &quot;valid_records&quot;: len(valid_data),<br>            &quot;invalid_records&quot;: len(race_data) - len(valid_data),<br>            &quot;errors&quot;: errors,<br>            &quot;success_rate&quot;: (len(valid_data) / len(race_data) * 100) if race_data else 0<br>        }<br>        <br>        self.validation_reports.append(validation_report)<br>        <br>        return valid_data, validation_report<br>    <br>    def get_overall_statistics(self):<br>        &quot;&quot;&quot;Calculate overall validation statistics across all processed races&quot;&quot;&quot;<br>        if not self.validation_reports:<br>            return {&quot;overall_success_rate&quot;: 0, &quot;total_records&quot;: 0, &quot;valid_records&quot;: 0}<br>        <br>        total_records = sum(r[&quot;total_records&quot;] for r in self.validation_reports)<br>        valid_records = sum(r[&quot;valid_records&quot;] for r in self.validation_reports)<br>        <br>        return {<br>            &quot;total_records&quot;: total_records,<br>            &quot;valid_records&quot;: valid_records,<br>            &quot;overall_success_rate&quot;: (valid_records / total_records * 100) if total_records &gt; 0 else 0,<br>            &quot;total_races&quot;: len(self.validation_reports)<br>        }<br></pre><pre>=== Data Collection Complete ===<br>Total records: 42518<br>Ferrari records: 4289<br>Other teams: 38229<br>Validation success rate: 99.9%</pre><h4>Now let’s build the core model logic:</h4><p>First let’s process the data and prepare it for model ingestion:</p><ol><li>We first convert raw F1 telemetry data (lap times, tire age, weather conditions) into 9 standardized features that machine<br> learning models can understand and process;</li></ol><pre>FEATURE_COLUMNS = [<br>    &#39;lap_number&#39;, &#39;lap_time&#39;, &#39;stint&#39;, <br>    &#39;tyre_age&#39;, &#39;fresh_tyre&#39;, &#39;position&#39;,<br>    &#39;air_temp&#39;, &#39;track_temp&#39;, &#39;weather_dry&#39;<br>]</pre><p>2. We handle missing or invalid race data automatically by using sensible defaults (like P10 for position, 22°C for temperature) so we don’t lose valuable training laps, keep the model robust when telemetry is incomplete, and prioritize having a strategy system that always works over one that’s perfectly accurate but might fail in real races;</p><p>3. We turn the messy real-world race data into clean pandas DataFrames with consistent column types : integers for laps, floats for times, booleans for conditions -&gt; because scikit-learn models need data to be neat and predictable, otherwise they give nonsense results.</p><pre>import pandas as pd<br>from typing import Dict, Tuple<br><br># Features used by the machine learning model<br>FEATURE_COLUMNS = [<br>    &#39;lap_number&#39;, &#39;lap_time&#39;, &#39;stint&#39;, <br>    &#39;tyre_age&#39;, &#39;fresh_tyre&#39;, &#39;position&#39;,<br>    &#39;air_temp&#39;, &#39;track_temp&#39;, &#39;weather_dry&#39;<br>]<br><br># Default values for missing race data<br>DEFAULTS = {<br>    &#39;position&#39;: 10,<br>    &#39;air_temp&#39;: 22.0,<br>    &#39;track_temp&#39;: 35.0,<br>    &#39;tyre_age&#39;: 0,<br>    &#39;fresh_tyre&#39;: False,<br>    &#39;weather_dry&#39;: True<br>}<br><br># Valid ranges for data validation<br>VALIDATION_RANGES = {<br>    &#39;lap_number&#39;: (1, 100),<br>    &#39;lap_time&#39;: (60.0, 200.0),<br>    &#39;stint&#39;: (1, 5),<br>    &#39;tyre_age&#39;: (0, 60),<br>    &#39;position&#39;: (1, 20),<br>    &#39;air_temp&#39;: (-10.0, 50.0),<br>    &#39;track_temp&#39;: (0.0, 70.0)<br>}<br><br><br>class F1DataProcessor:<br>    @staticmethod<br>    def process_race_data_for_training(race_data) -&gt; pd.DataFrame:<br>        &quot;&quot;&quot;Convert raw race data into clean DataFrame ready for model training&quot;&quot;&quot;<br>        data = []<br>        <br>        for record in race_data:<br>            if not record.compound or not record.lap_time:<br>                continue<br>                <br>            try:<br>                features = {<br>                    &#39;lap_number&#39;: record.lap or 1,<br>                    &#39;lap_time&#39;: float(record.lap_time),<br>                    &#39;stint&#39;: record.stint or 1,<br>                    &#39;tyre_age&#39;: record.tyre_age if record.tyre_age is not None else DEFAULTS[&#39;tyre_age&#39;],<br>                    &#39;fresh_tyre&#39;: bool(record.fresh_tyre if record.fresh_tyre is not None else DEFAULTS[&#39;fresh_tyre&#39;]),<br>                    &#39;position&#39;: record.position or DEFAULTS[&#39;position&#39;],<br>                    &#39;air_temp&#39;: record.air_temp or DEFAULTS[&#39;air_temp&#39;],<br>                    &#39;track_temp&#39;: record.track_temp or DEFAULTS[&#39;track_temp&#39;],<br>                    &#39;weather_dry&#39;: F1DataProcessor._is_dry_weather(record.weather_condition),<br>                    &#39;compound&#39;: record.compound,<br>                    &#39;team&#39;: record.team or &#39;Unknown&#39;,<br>                    &#39;driver&#39;: record.driver,<br>                    &#39;round&#39;: record.round,<br>                    &#39;race_name&#39;: record.race_name,<br>                    &#39;is_ferrari&#39;: bool(record.is_ferrari) if hasattr(record, &#39;is_ferrari&#39;) else False<br>                }<br>                <br>                features = F1DataProcessor._validate_ranges(features)<br>                data.append(features)<br>                <br>            except (ValueError, AttributeError):<br>                continue<br>        <br>        df = pd.DataFrame(data)<br>        if not df.empty:<br>            df[&#39;fresh_tyre&#39;] = df[&#39;fresh_tyre&#39;].astype(int)<br>            df[&#39;weather_dry&#39;] = df[&#39;weather_dry&#39;].astype(int)<br>            df[&#39;is_ferrari&#39;] = df[&#39;is_ferrari&#39;].astype(bool)<br>        <br>        return df<br>    <br>    @staticmethod<br>    def prepare_features_for_prediction(features: Dict) -&gt; pd.DataFrame:<br>        &quot;&quot;&quot;Convert feature dictionary to DataFrame for model prediction&quot;&quot;&quot;<br>        for feature in FEATURE_COLUMNS:<br>            if feature not in features and feature in DEFAULTS:<br>                features[feature] = DEFAULTS[feature]<br>        <br>        features[&#39;lap_number&#39;] = int(features[&#39;lap_number&#39;])<br>        features[&#39;stint&#39;] = int(features[&#39;stint&#39;])<br>        features[&#39;tyre_age&#39;] = int(features[&#39;tyre_age&#39;])<br>        features[&#39;position&#39;] = int(features[&#39;position&#39;])<br>        features[&#39;fresh_tyre&#39;] = bool(features[&#39;fresh_tyre&#39;])<br>        features[&#39;weather_dry&#39;] = bool(features[&#39;weather_dry&#39;])<br>        <br>        features = F1DataProcessor._validate_ranges(features)<br>        <br>        features_data = [[<br>            features[&#39;lap_number&#39;], <br>            features[&#39;lap_time&#39;], <br>            features[&#39;stint&#39;],<br>            features[&#39;tyre_age&#39;], <br>            int(features[&#39;fresh_tyre&#39;]), <br>            features[&#39;position&#39;],<br>            features[&#39;air_temp&#39;], <br>            features[&#39;track_temp&#39;], <br>            int(features[&#39;weather_dry&#39;])<br>        ]]<br>        <br>        return pd.DataFrame(features_data, columns=FEATURE_COLUMNS)<br>    <br>    @staticmethod<br>    def split_features_and_target(df: pd.DataFrame) -&gt; Tuple[pd.DataFrame, pd.Series]:<br>        &quot;&quot;&quot;Split DataFrame into features (X) and target (y) for model training&quot;&quot;&quot;<br>        X = df[FEATURE_COLUMNS].copy()<br>        y = df[&#39;compound&#39;].copy()<br>        return X, y<br>    <br>    @staticmethod<br>    def _is_dry_weather(weather_condition) -&gt; bool:<br>        &quot;&quot;&quot;Check if weather conditions are dry&quot;&quot;&quot;<br>        if not weather_condition:<br>            return DEFAULTS[&#39;weather_dry&#39;]<br>        <br>        weather_str = str(weather_condition).upper()<br>        wet_conditions = [&#39;WET&#39;, &#39;RAIN&#39;, &#39;INTERMEDIATE&#39;, &#39;DAMP&#39;]<br>        return not any(condition in weather_str for condition in wet_conditions)<br>    <br>    @staticmethod<br>    def _validate_ranges(features: Dict) -&gt; Dict:<br>        &quot;&quot;&quot;Ensure feature values are within reasonable ranges&quot;&quot;&quot;<br>        validated = features.copy()<br>        <br>        for feature, value in features.items():<br>            if feature in VALIDATION_RANGES:<br>                min_val, max_val = VALIDATION_RANGES[feature]<br>                if isinstance(value, (int, float)):<br>                    if value &lt; min_val or value &gt; max_val:<br>                        validated[feature] = max(min_val, min(max_val, value))<br>        <br>        return validated</pre><h4>Train the Random Forest model:</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJ4Wdy0Wc_xQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJ4Wdy0Wc_xQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJ4Wdy0Wc_xQ%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b33b62542ee896d00d45fda6d0aad8b/href">https://medium.com/media/0b33b62542ee896d00d45fda6d0aad8b/href</a></iframe><p>We went with Random Forest instead of neural networks because F1 datasets are tiny, around 20K laps max per season, while neural nets need millions of samples to avoid overfitting (F1 teams have access to a lot more data points then there are publicly available so a neural approach might still be feasible). Random Forest handles small tabular data well and even shows which features matter most, like lap number and position for tire choice.</p><p>Monte Carlo simulations were out too, because those need probability distributions for everything (tire wear, weather, other drivers), and we don’t have enough domain knowledge to model that accurately. Random Forest can just learn patterns directly from historical data.</p><p>To prevent overfitting, we set max_depth=15 and min_samples_split=10, assuming most strategy decisions can be captured in a 15-level tree and requiring 10 samples per split stops the model from memorizing crazy outliers like Spa rain chaos.</p><p>For features, we focus on track position, lap timing, and stint age, basically what F1 teams actually care about, rather than trying to model every tiny interaction that would need a deep neural net. We validate with an 80/20 train/test split and <a href="https://medium.com/data-science/what-is-out-of-bag-oob-score-in-random-forest-a7fa23d710">out-of-bag scoring</a> so the model isn’t tested on data it already saw.</p><p>Finally, real-world deployment needs explainable AI: Random Forest can say “we picked SOFT because lap number and position mattered,” whereas neural nets are black boxes. In F1, interpretable decisions beat tiny accuracy gains.</p><pre>import joblib<br>import os<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score<br>import sys<br>sys.path.insert(0, os.path.join(os.path.dirname(__file__), &#39;..&#39;))<br><br>from data.database import Database<br>from data.entities import RaceData<br>from data_processor import F1DataProcessor<br><br><br>def train_tire_strategy_model(): <br>    &quot;&quot;&quot;Train a Random Forest model to predict tire compounds from F1 race data&quot;&quot;&quot;<br>    print(&quot;Loading race data from database...&quot;)<br>    db = Database()<br>    with db.get_session() as session:<br>        race_data = session.query(RaceData).all()<br>        <br>        if not race_data:<br>            print(&quot;Error: No data found in database. Please fetch race data first.&quot;)<br>            return None<br>    <br>    print(f&quot;Processing {len(race_data)} race records...&quot;)<br>    df = F1DataProcessor.process_race_data_for_training(race_data)<br>    <br>    if df.empty:<br>        print(&quot;Error: No valid training data after processing.&quot;)<br>        return None<br>    <br>    X, y = F1DataProcessor.split_features_and_target(df)<br>    print(f&quot;Training with {len(X)} samples and {len(y.unique())} tire compounds: {list(y.unique())}&quot;)<br>    <br>    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br>    <br>    print(&quot;Training Random Forest model...&quot;)<br>    model = RandomForestClassifier(<br>        n_estimators=100,<br>        max_depth=15,<br>        min_samples_split=10,<br>        min_samples_leaf=5,<br>        random_state=42,<br>        oob_score=True<br>    )<br>    model.fit(X_train, y_train)<br>    <br>    y_pred = model.predict(X_test)<br>    test_accuracy = accuracy_score(y_test, y_pred)<br>    <br>    print(f&quot;\nTraining Complete!&quot;)<br>    print(f&quot;Test Accuracy: {test_accuracy:.2%}&quot;)<br>    print(f&quot;Out-of-Bag Score: {model.oob_score_:.2%}&quot;)<br>    <br>    model_path = os.path.join(os.path.dirname(__file__), &quot;..&quot;, &quot;..&quot;, &quot;models&quot;, &quot;tire_strategy_model.pkl&quot;)<br>    os.makedirs(os.path.dirname(model_path), exist_ok=True)<br>    joblib.dump(model, model_path)<br>    print(f&quot;Model saved to: {model_path}&quot;)<br>    <br>    sample_features = {<br>        &#39;lap_number&#39;: 10, &#39;lap_time&#39;: 90.5, &#39;stint&#39;: 1, &#39;tyre_age&#39;: 4, &#39;fresh_tyre&#39;: False,<br>        &#39;position&#39;: 5, &#39;air_temp&#39;: 22.0, &#39;track_temp&#39;: 35.0, &#39;weather_dry&#39;: True<br>    }<br>    <br>    features_df = F1DataProcessor.prepare_features_for_prediction(sample_features)<br>    prediction = model.predict(features_df)[0]<br>    confidence = max(model.predict_proba(features_df)[0])<br>    <br>    print(f&quot;\nTest prediction: {prediction} (confidence: {confidence:.2%})&quot;)<br>    <br>    return model<br><br><br>if __name__ == &quot;__main__&quot;:<br>    train_tire_strategy_model()</pre><p>Now onto the F1 Strategy Engine: the “race strategist brain” that considers tire physics, race timing, and model predictions together</p><p>Our strategy engine is built on a simple F1 truth: tire degradation drives pit stop timing. <strong>Fresher tires are always faster, and the goal is to balance tire life with track position, since a pit stop typically costs 20–25 seconds.</strong></p><p>We hardcoded tire degradation rates based on F1 data: SOFT tires lose 8% per lap (fast but short-lived), MEDIUM 5% (balanced), and HARD 3% (slow but durable), assuming each 1% loss adds about 0.02 seconds per lap.</p><p>Tires also go through three phases: Fresh (0–5 laps, slower wear), Linear (6–15 laps, standard), and Cliff (15+ laps, faster wear).</p><p>Pit stop windows follow F1 logic: early windows (laps 15–25) target two-stop strategies, standard windows (30–45) are for one-stop plans, and late windows (50+) are sprints with fresh soft tires. The ML model we will talk about next predicts the best compound but falls back on rules: short runs get SOFT, long runs HARD, medium runs MEDIUM.</p><p>Track position matters more for cars higher up the grid, since undercut and overcut threats are bigger, so pit timing adjusts accordingly. We simplify other factors too : no safety cars, consistent weather, standard pit times, and all drivers assumed to have similar pace in order to create a solid baseline strategy.</p><p>The ML model is only used for compound selection, it predicts whether to use SOFT/MEDIUM/HARD tires for the next stint. But the strategy<br>engine determines WHEN to pit (based on degradation physics) and WHY to pit (based on race windows) using its own logic.</p><p>Think of it this way:<br><em>1. Model says: “Use MEDIUM tires next”<br>2. Strategy engine says: “Pit on lap 32 for MEDIUM tires because your current SOFT tires will hit the degradation cliff, you’re in the standard <br>pit window, and track position allows it”</em></p><pre>from typing import Dict<br>from .model import TireStrategyModel<br><br><br>class StrategyEngine:    <br>    def __init__(self):<br>        self.tire_model = TireStrategyModel()<br>        self._is_model_loaded = False<br>        <br>    def generate_race_strategy(self, session_data: Dict) -&gt; Dict:<br>        &quot;&quot;&quot;Generate complete F1 race strategy analysis from session data&quot;&quot;&quot;<br>        if not self._is_model_loaded:<br>            self.tire_model.load_model()<br>            self._is_model_loaded = True<br>        <br>        current_lap = session_data.get(&#39;current_lap&#39;, 1)<br>        total_laps = session_data.get(&#39;total_laps&#39;, 70)<br>        current_compound = session_data.get(&#39;current_compound&#39;, &#39;MEDIUM&#39;)<br>        stint_age = session_data.get(&#39;stint_age&#39;, 1)<br>        current_position = session_data.get(&#39;current_position&#39;, 10)<br>        last_lap_time = session_data.get(&#39;last_lap_time&#39;, 90.0)<br>        <br>        laps_remaining = total_laps - current_lap<br>        <br>        degradation = self._calculate_tire_degradation(current_compound, stint_age)<br>        pit_recommendations = self._generate_pit_recommendations(current_lap, laps_remaining, current_compound, stint_age)<br>        compound_recommendation = self._predict_best_compound(current_lap, last_lap_time, current_position, laps_remaining)<br>        <br>        strategy_summary = f&quot;P{current_position} Lap {current_lap}/{total_laps}: &quot;<br>        if pit_recommendations:<br>            best_pit = pit_recommendations[0]<br>            laps_to_pit = best_pit[&#39;recommended_lap&#39;] - current_lap<br>            strategy_summary += f&quot;Pit in {laps_to_pit} laps → {compound_recommendation[&#39;compound&#39;]}&quot;<br>        else:<br>            strategy_summary += f&quot;Stay out on {current_compound} - {laps_remaining} laps remaining&quot;<br>        <br>        return {<br>            &#39;current_analysis&#39;: {<br>                &#39;current_lap&#39;: current_lap,<br>                &#39;current_compound&#39;: current_compound,<br>                &#39;stint_age&#39;: stint_age,<br>                &#39;laps_remaining&#39;: laps_remaining,<br>                &#39;current_position&#39;: current_position,<br>                &#39;race_progress&#39;: round((current_lap / total_laps) * 100, 1)<br>            },<br>            &#39;tire_degradation&#39;: degradation,<br>            &#39;pit_recommendations&#39;: pit_recommendations,<br>            &#39;compound_recommendation&#39;: compound_recommendation,<br>            &#39;strategy_summary&#39;: strategy_summary,<br>            &#39;recommendations_count&#39;: len(pit_recommendations)<br>        }<br>    <br>    def _calculate_tire_degradation(self, compound: str, stint_age: int) -&gt; Dict:<br>        &quot;&quot;&quot;Calculate tire degradation based on compound and stint age&quot;&quot;&quot;<br>        degradation_rates = {&#39;SOFT&#39;: 0.08, &#39;MEDIUM&#39;: 0.05, &#39;HARD&#39;: 0.03}<br>        <br>        base_rate = degradation_rates.get(compound, 0.05)<br>        <br>        if stint_age &lt;= 5:<br>            degradation = base_rate * stint_age * 0.7<br>        elif stint_age &lt;= 15:<br>            degradation = base_rate * stint_age<br>        else:<br>            degradation = base_rate * stint_age * 1.3<br>        <br>        degradation = min(degradation, 0.95)<br>        <br>        if stint_age &lt;= 5:<br>            phase = &quot;Fresh - Minimal degradation&quot;<br>        elif stint_age &lt;= 15:<br>            phase = &quot;Linear - Steady degradation&quot;<br>        else:<br>            phase = &quot;Accelerated - Rapid degradation&quot;<br>        <br>        return {<br>            &#39;compound&#39;: compound,<br>            &#39;stint_age&#39;: stint_age,<br>            &#39;degradation_percent&#39;: round(degradation, 3),<br>            &#39;estimated_lap_time_delta&#39;: round(degradation * 2.0, 2),<br>            &#39;degradation_phase&#39;: phase<br>        }<br>    <br>    def _generate_pit_recommendations(self, current_lap: int, laps_remaining: int, current_compound: str, stint_age: int) -&gt; list:<br>        &quot;&quot;&quot;Generate pit stop recommendations based on race situation&quot;&quot;&quot;<br>        recommendations = []<br>        <br>        if 15 &lt;= current_lap &lt;= 25 and laps_remaining &gt; 30:<br>            recommendations.append({<br>                &#39;window_type&#39;: &#39;Early&#39;,<br>                &#39;recommended_lap&#39;: current_lap + 3,<br>                &#39;target_compound&#39;: &#39;HARD&#39; if current_compound != &#39;HARD&#39; else &#39;MEDIUM&#39;,<br>                &#39;reason&#39;: f&#39;Early stop for long second stint ({laps_remaining} laps remaining)&#39;,<br>                &#39;confidence&#39;: 0.6 if laps_remaining &gt; 35 else 0.4<br>            })<br>        <br>        if 30 &lt;= current_lap &lt;= 45 and laps_remaining &gt; 15:<br>            target = &#39;MEDIUM&#39; if current_compound == &#39;SOFT&#39; else &#39;SOFT&#39;<br>            confidence = 0.9 if 25 &lt;= laps_remaining &lt;= 35 else 0.7<br>            recommendations.append({<br>                &#39;window_type&#39;: &#39;Standard&#39;,<br>                &#39;recommended_lap&#39;: current_lap + 5,<br>                &#39;target_compound&#39;: target,<br>                &#39;reason&#39;: f&#39;Standard strategy window ({laps_remaining} laps to finish)&#39;,<br>                &#39;confidence&#39;: confidence<br>            })<br>        <br>        if current_lap &gt;= 50 and laps_remaining &gt; 15:<br>            recommendations.append({<br>                &#39;window_type&#39;: &#39;Late&#39;,<br>                &#39;recommended_lap&#39;: current_lap + min(8, laps_remaining - 12),<br>                &#39;target_compound&#39;: &#39;SOFT&#39;,<br>                &#39;reason&#39;: f&#39;Late stop for fresh tire advantage in final {laps_remaining} laps&#39;,<br>                &#39;confidence&#39;: 0.8 if laps_remaining &gt; 20 else 0.6<br>            })<br>        <br>        return sorted([r for r in recommendations if r[&#39;recommended_lap&#39;] &gt; current_lap], <br>                     key=lambda x: x[&#39;confidence&#39;], reverse=True)<br>    <br>    def _predict_best_compound(self, current_lap: int, last_lap_time: float, current_position: int, laps_remaining: int) -&gt; Dict:<br>        &quot;&quot;&quot;Predict best tire compound using ML model with fallback logic&quot;&quot;&quot;<br>        try:<br>            next_stint_lap = current_lap + 15<br>            <br>            features = {<br>                &#39;lap_number&#39;: next_stint_lap,<br>                &#39;lap_time&#39;: last_lap_time,<br>                &#39;stint&#39;: 2,<br>                &#39;tyre_age&#39;: 0,<br>                &#39;fresh_tyre&#39;: True,<br>                &#39;position&#39;: current_position,<br>                &#39;air_temp&#39;: 22.0,<br>                &#39;track_temp&#39;: 35.0,<br>                &#39;weather_dry&#39;: True<br>            }<br>            <br>            prediction = self.tire_model.predict_compound_from_features(features)<br>            <br>            return {<br>                &#39;compound&#39;: prediction[&#39;compound&#39;],<br>                &#39;confidence&#39;: round(prediction[&#39;confidence&#39;], 3),<br>                &#39;reasoning&#39;: f&quot;ML prediction for lap {next_stint_lap}, P{current_position}&quot;<br>            }<br>            <br>        except Exception:<br>            if laps_remaining &lt; 20:<br>                compound = &#39;SOFT&#39;<br>                reason = &quot;Short remaining distance - soft compound&quot;<br>            elif laps_remaining &gt; 40:<br>                compound = &#39;HARD&#39;<br>                reason = &quot;Long remaining distance - hard compound&quot;<br>            else:<br>                compound = &#39;MEDIUM&#39;<br>                reason = &quot;Medium distance - balanced strategy&quot;<br>            <br>            return {<br>                &#39;compound&#39;: compound,<br>                &#39;confidence&#39;: 0.5,<br>                &#39;reasoning&#39;: reason<br>            }</pre><p>The final file in the core module is the TireStrategyModel which loads the model, automatically converts raw features into the right DataFrame format, returns both tire predictions and confidence scores, and checks that the model is loaded to avoid crashes during race strategy analysis. Straight to the point…</p><pre>import joblib<br>import os<br>from typing import Dict<br>from data_processor import F1DataProcessor<br><br><br>class TireStrategyModel:<br>    def __init__(self):<br>        self.model = None<br>        self.model_path = os.path.join(os.path.dirname(__file__), &quot;..&quot;, &quot;..&quot;, &quot;models&quot;, &quot;tire_strategy_model.pkl&quot;)<br>    <br>    def load_model(self) -&gt; None:<br>        if not os.path.exists(self.model_path):<br>            raise FileNotFoundError(f&quot;Model file not found: {self.model_path}&quot;)<br>        <br>        self.model = joblib.load(self.model_path)<br>    <br>    def predict_compound_from_features(self, features: Dict) -&gt; Dict:<br>        if self.model is None:<br>            raise ValueError(&quot;Model not loaded. Call load_model() first.&quot;)<br>        <br>        features_df = F1DataProcessor.prepare_features_for_prediction(features)<br>        <br>        prediction = self.model.predict(features_df)[0]<br>        confidence = max(self.model.predict_proba(features_df)[0])<br>        <br>        return {<br>            &#39;compound&#39;: prediction,<br>            &#39;confidence&#39;: confidence<br>        }</pre><pre>  Processing 42518 race records...<br>  Training with 41966 samples and 5 tire compounds: [&#39;SOFT&#39;, &#39;HARD&#39;, &#39;MEDIUM&#39;, &#39;INTERMEDIATE&#39;, &#39;WET&#39;]<br>  Training Random Forest model...<br><br>  Training Complete!<br>  Test Accuracy: 78.16%<br>  Out-of-Bag Score: 78.03%</pre><p>This doesn’t appear to be overfitting as the training and out-of-bag scores are very close (78.16% vs 78.03%), indicating the model generalizes well. :)</p><h4>How good is our model?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XeI-pEFaEkMen0Y-EEypeg.png" /><figcaption>Model accuracy on our test data</figcaption></figure><pre>  {<br>    &quot;model_overview&quot;: {<br>      &quot;overall_accuracy&quot;: &quot;78.2%&quot;,<br>      &quot;total_test_samples&quot;: 8394,<br>      &quot;average_confidence&quot;: &quot;70.3%&quot;,<br>      &quot;compounds_analyzed&quot;: 5<br>    },<br>    &quot;compound_performance&quot;: {<br>      &quot;HARD&quot;: {<br>        &quot;accuracy&quot;: &quot;89.8%&quot;,<br>        &quot;sample_count&quot;: 4181,<br>        &quot;precision&quot;: &quot;0.79&quot;,<br>        &quot;recall&quot;: &quot;0.90&quot;,<br>        &quot;f1_score&quot;: &quot;0.84&quot;<br>      },<br>      &quot;INTERMEDIATE&quot;: {<br>        &quot;accuracy&quot;: &quot;46.0%&quot;,<br>        &quot;sample_count&quot;: 367,<br>        &quot;precision&quot;: &quot;0.88&quot;,<br>        &quot;recall&quot;: &quot;0.46&quot;,<br>        &quot;f1_score&quot;: &quot;0.60&quot;<br>      },<br>      &quot;MEDIUM&quot;: {<br>        &quot;accuracy&quot;: &quot;71.6%&quot;,<br>        &quot;sample_count&quot;: 2866,<br>        &quot;precision&quot;: &quot;0.74&quot;,<br>        &quot;recall&quot;: &quot;0.72&quot;,<br>        &quot;f1_score&quot;: &quot;0.73&quot;<br>      },<br>      &quot;SOFT&quot;: {<br>        &quot;accuracy&quot;: &quot;60.0%&quot;,<br>        &quot;sample_count&quot;: 967,<br>        &quot;precision&quot;: &quot;0.82&quot;,<br>        &quot;recall&quot;: &quot;0.60&quot;,<br>        &quot;f1_score&quot;: &quot;0.69&quot;<br>      },<br>      &quot;WET&quot;: {<br>        &quot;accuracy&quot;: &quot;38.5%&quot;,<br>        &quot;sample_count&quot;: 13,<br>        &quot;precision&quot;: &quot;1.00&quot;,<br>        &quot;recall&quot;: &quot;0.38&quot;,<br>        &quot;f1_score&quot;: &quot;0.56&quot;<br>      }<br>    },<br>    &quot;confidence_analysis&quot;: {<br>      &quot;high_confidence_predictions&quot;: 2802,<br>      &quot;high_confidence_accuracy&quot;: &quot;96.3%&quot;,<br>      &quot;high_confidence_threshold&quot;: &quot;80%&quot;<br>    },<br>    &quot;detailed_metrics&quot;: {<br>      &quot;precision_weighted&quot;: &quot;0.78&quot;,<br>      &quot;recall_weighted&quot;: &quot;0.78&quot;,<br>      &quot;f1_score_weighted&quot;: &quot;0.78&quot;<br>    }<br>  }</pre><p>Our F1 tire strategy model was evaluated using standard classification metrics on 8,394 test samples across five tire compounds.</p><p>We chose accuracy, precision, recall, and F1-score as our primary metrics, along with confidence analysis to understand prediction reliability. The model achieved an overall accuracy of 78.2% with very good performance on hard compounds (89.8% accuracy), solid results for medium compounds (71.6%), but struggled with weather-dependent tires like intermediates (46.0%) and wets (38.5%) due to limited training data.</p><p>Most importantly, when the model expressed high confidence (&gt;80% probability), it achieved 96.3% accuracy across 2,802 predictions, demonstrating strong reliability for strategic decision-making in race conditions.</p><h4>Now how does that compare with Ferrari?</h4><p>The analysis shows an 87.2% match between Ferrari’s 2024 strategy calls and our AI model across 1,876 decisions. That’s a strong alignment, with only 18 high-confidence disagreements (about 1%) where the AI was more than 75% sure a different tire choice would’ve been better. <strong>Important note: this is based on Ferrari’s actual 2024 season results, not 2025.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rrz7rBTCTdmHp2y17MsZYA.png" /><figcaption>Ferrari vs AI Strategy Model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f_pmNERarkvUtywgRkjiIg.png" /></figure><p><strong>Belgian GP (10 disagreements — 55% of all disagreements):</strong> Ferrari finished Leclerc P3 (after Russell’s DQ) and Sainz P6. The AI disagreed mostly on laps 3–11 (wanted Mediums over Ferrari’s Hards, 85%+ confidence) and laps 23–26 (wanted Hards over Mediums, ~75–77% confidence). Hot track temps made Hards the smart call — Sainz started on Hards and performed well, while Ferrari split strategies to hedge risks. The AI pushed for Mediums early, but Ferrari’s approach was validated; our model likely underestimated how much track temperature favored durability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R8DFaY2-6NwuWSk6oe2wBQ.png" /></figure><p><strong>Canadian GP (3 disagreements):</strong> Ferrari had a nightmare (quite common for them) weekend with a double DNF — Leclerc retired with power unit issues, and Sainz crashed in the wet. The AI disagreed three times (laps 2, 8, 10), preferring Mediums over Intermediates with ~79% confidence. But this was a rain race where Intermediates were mandatory; using Mediums would’ve been unsafe. Ferrari’s call was correct, and the AI’s suggestion highlights a key limitation: it doesn’t properly account for weather conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JcTlluzFRjXIP3x1PXMrcw.png" /><figcaption>(FYI: first column is Ferrari Strategy second column is AI Strategy — the colors don’t match for the second and third representations)</figcaption></figure><p><strong>Spanish GP (3 disagreements):</strong> Ferrari finished as they started — Leclerc P5, Sainz P6. The AI disagreed on lap 1 (wanted Mediums instead of Softs, 85% confidence) and later on laps 36 and 47 (wanted Hards over Mediums, ~77–83% confidence). Ferrari split strategies: Sainz ran Soft-Medium-Hard, while Leclerc went Soft-Medium-Soft, which the team said “paid off better.” The AI’s push for Mediums at the start and Hards later overlooks key factors like qualifying tire rules and track position. Ferrari’s approach was intentional, and by their own assessment, the Soft-focused strategy worked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2mEnCePGGbbTZRAEJ3OX6Q.png" /></figure><p><strong>Japanese GP (2 disagreements):</strong> Ferrari executed flawlessly, Sainz P3, Leclerc P4. The AI disagreed on laps 26 and 36, preferring Hards over Ferrari’s Mediums (~78% confidence). Ferrari ran contrasting strategies: Leclerc on a one-stop (Medium→Hard on lap 26) and Sainz on a two-stop with fresher Hards, letting him charge through the field for the podium. The AI missed the nuance of this split approach, overvaluing Hards when Mediums were the smarter choice.</p><h4>What about the 2025 races?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ou-CRRZV6bxb_wsh6FaXg.png" /></figure><p>In the 2025 Australian GP, 81% of all teams chose Intermediates for wet conditions, but the AI predicted 0% Intermediates, instead suggesting Hards and Softs. In other words, it completely missed the weather. Across three wet races, the AI’s accuracy averaged just 8%, showing it can’t recognize patterns that human strategists spot immediately.</p><p>Meanwhile, Ferrari’s human teams adapted quite good: in dry races like Austria and Saudi Arabia, they matched the AI predictions 100%, and in tricky conditions like Canada, they made smart weather-aware choices far beyond the AI’s capabilities. Well… turns out we didn’t manage to build a better AI strategist than Ferrari, maybe they’re actually smarter than I thought 😅.</p><p>Lesson learned: predicting F1 strategy is way harder than it looks, and humans still have the upper hand when it comes to subtle, lap-by-lap decisions.</p><p>Key problems: oversimplified weather handling led to 46% accuracy on Intermediates and 38.5% on Wets, while Hards hit 89.8%.</p><p><strong>How to improve:</strong> add detailed weather data, include strategic context (gaps, laps, pit windows, safety car probability), model lap sequences with LSTM/GRU, split models by weather, augment wet data, use real-time confidence thresholds, and consider ensemble architectures.</p><p>Forza Ferrari!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=238c3ab7d4d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>