<?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 Svitlana Kokhatska on Medium]]></title>
        <description><![CDATA[Stories by Svitlana Kokhatska on Medium]]></description>
        <link>https://medium.com/@skokhatska?source=rss-8fcb7662e908------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pplUX1OdiYAvLfbezRuG2g.png</url>
            <title>Stories by Svitlana Kokhatska on Medium</title>
            <link>https://medium.com/@skokhatska?source=rss-8fcb7662e908------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 18:49:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@skokhatska/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[Unveiling Dubai’s Real Estate (Part 4): Using Machine Learning to Value Properties]]></title>
            <link>https://medium.com/@skokhatska/unveiling-dubais-real-estate-a-data-driven-dive-part-4-3721334d76d3?source=rss-8fcb7662e908------2</link>
            <guid isPermaLink="false">https://medium.com/p/3721334d76d3</guid>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[model-training]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Svitlana Kokhatska]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 21:52:25 GMT</pubDate>
            <atom:updated>2025-09-01T21:52:25.835Z</atom:updated>
            <content:encoded><![CDATA[<h4>Applying machine learning to turn real estate data into actionable price predictions</h4><h4>Training and tuning a model that explains 95% of price variance — and uncovers the key drivers of Dubai’s property values</h4><h3>Recap and the Road Ahead</h3><p>In <strong>Part 4</strong> of our series, we shift focus to <strong>predictive modeling</strong>. With a clean, feature-rich dataset in hand (from Parts <a href="https://medium.com/@skokhatska/unveiling-dubais-real-estate-a-data-driven-dive-part-1-dfca41c5d1a6">1</a>–<a href="https://medium.com/@skokhatska/unveiling-dubais-real-estate-a-data-driven-dive-part-3-e2c4e178408d">3</a>), our goal is to train an <strong>XGBoost Regressor</strong> to predict Dubai property sale prices. We’ll cover how we split the data for training and validation, set up the XGBoost model, tune hyperparameters, and evaluate performance. By the end, we’ll interpret the model’s results (accuracy, errors, and feature importance) and discuss next steps like deployment and forecasting.</p><h3>Data Split and Preparation</h3><p>To ensure reliable evaluation, we partitioned the data into <strong>training, validation, and test sets</strong>. We used an <strong>80/10/10</strong> split: first an 80/20 train-test split, then we further split that 20% into equal validation and final test sets. This yields roughly 80% of the data for model training, 10% for tuning/early stopping, and a final 10% for an unbiased test evaluation. The target variable actual_worth (sale price) is highly skewed, so we apply a <strong>log transformation</strong> (log1p) to make the distribution more modeling-friendly.</p><p>We also log-transform the property size (procedure_area) feature, since real estate prices often scale non-linearly with size. Categorical features (like property type, area, etc.) are already encoded as pandas category dtype (per our feature engineering in <a href="https://medium.com/@skokhatska/unveiling-dubais-real-estate-a-data-driven-dive-part-3-e2c4e178408d">Part 3</a>), allowing XGBoost to treat them natively without one-hot expansion.</p><p><strong>Note:</strong> Because we used scikit-learn’s train_test_split (which shuffles by default), this partition is <strong>random with respect to time</strong>. While this approach ensures an unbiased evaluation (no leakage between train and test), it doesn’t mimic a true chronological split – a limitation if our goal were strictly forecasting future sales based on past data.</p><pre>target_feature = &#39;actual_worth&#39;<br><br># Log-transform the target<br>y = np.log1p(df_final[target_feature])  # log1p for log(1 + x) to safely handle 0<br><br># Prepare features<br>X = df_final.drop([target_feature], axis=1)<br><br># Log-transform the &#39;area&#39; feature<br>if &#39;procedure_area&#39; in X.columns:<br>    X[&#39;procedure_area&#39;] = np.log1p(X[&#39;procedure_area&#39;])<br>else:<br>    raise KeyError(&quot;&#39;procedure_area&#39; feature not found in the dataset&quot;)<br><br># Split the data into training and testing sets (80/20)<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)<br><br># Split the 20% chunk equally into validation and final test (10% each overall)<br>X_test, X_val, y_test, y_val = train_test_split(<br>    X_test, y_test, test_size=0.5, random_state=42<br>)</pre><p>With data prepared (and the target and key feature scaled logarithmically), we’re ready to train the model.</p><h3>Initial XGBoost Model Setup</h3><p>We chose <strong>XGBoost</strong> for its efficiency and ability to handle large structured data. Our model’s objective is standard regression (reg:squarederror for RMSE). We initially set reasonable default hyperparameters based on domain intuition:</p><pre>model = XGBRegressor(<br>    objective=&#39;reg:squarederror&#39;,<br>    learning_rate=0.1,    # step size shrinkage<br>    max_depth=15,         # tree depth (controls complexity)<br>    n_estimators=100,     # maximum trees (with early stopping)<br>    eval_metric=&#39;rmse&#39;,   # optimize RMSE during training<br>    early_stopping_rounds=10,<br>    enable_categorical=True, # handle category dtype directly<br>    reg_alpha=1, reg_lambda=1,  # moderate L1/L2 regularization<br>    random_state=42<br>)</pre><p>We include an early_stopping_rounds=10 parameter so that if the validation RMSE doesn’t improve for 10 rounds, training stops early to prevent overfitting. We add moderate L1 (reg_alpha) and L2 (reg_lambda) regularization to further tame model complexity. The relatively high <strong>max_depth=10</strong> allows trees to capture complex interactions (since our data has many features), while the <strong>learning_rate=0.1</strong> balances training speed and convergence (lower values make training more robust but slower).</p><p>Next, we fit this model on the training set and monitor performance on the validation set:</p><pre>model.fit(<br>    X_train, y_train,<br>    eval_set=[(X_train, y_train), (X_val, y_val)],<br>    verbose=False  # silent training<br>)</pre><p>The eval_set includes both training and validation so we can track both curves. The model’s initial validation R² was about <strong>0.95</strong>, indicating that even untuned, it explained ~95% of the variance on the validation set. Early stopping kicked in before all 100 trees were built, suggesting we hadn’t severely overfit.</p><pre>plt.scatter(x=training_rounds,y=eval_result[&#39;validation_0&#39;][&#39;rmse&#39;],label=&#39;Training Error&#39;)<br>plt.scatter(x=training_rounds,y=eval_result[&#39;validation_1&#39;][&#39;rmse&#39;],label=&#39;Validation Error&#39;)<br>plt.grid(True)<br>plt.xlabel(&#39;Iteration&#39;)<br>plt.ylabel(&#39;RMSE&#39;)<br>plt.title(&#39;Training Vs Validation Error&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*FJ0vR9k-apshdpPmOGx6iw.png" /></figure><p><strong><em>Observation:</em></strong><em><br>The model reached its best performance at </em><strong><em>iteration 99</em></strong><em>, with a validation RMSE of </em><strong><em>0.1707</em></strong> <em>and a training RMSE of </em><strong><em>0.1558</em></strong><em>, resulting in a gap of about </em><strong><em>0.015</em></strong><em> that indicates a bit of overfitting was beginning by that point. Training error steadily declined with each round, while validation error dropped sharply in the first ~20 iterations, then improved gradually before plateauing. Early stopping at this point captured the model’s optimal balance between accuracy and generalization, preventing the overfitting gap from widening further.</em></p><h3>Hyperparameter Tuning</h3><p>While the initial model was a good start, we employed <strong>Randomized Search</strong> to fine-tune hyperparameters and squeeze out extra accuracy. Using RandomizedSearchCV (3-fold CV, 50 iterations), we searched over a broad range of values:</p><ul><li>max_depth<strong>:</strong> 10 to 25 (tree depth)</li><li>learning_rate<strong>:</strong> 0.01 to 0.10 (shrinkage)</li><li>n_estimators<strong>:</strong> 50 to 200 (number of trees)</li><li>subsample<strong>:</strong> 0.5 to 1.0 (fraction of training samples per tree)</li><li>reg_alpha<strong>:</strong> {0, 1, 5} (L1 regularization strength)</li><li>reg_lambda<strong>:</strong> 10⁰ to 10² (1 to 100, log-spaced L2 regularization)</li></ul><p>Crucially, we kept some parameters fixed — e.g. objective, eval_metric=&#39;rmse&#39;, colsample_bytree=0.5 (to sample half the features per tree for diversity), and tree_method=&#39;hist&#39; for speed on large data. The randomized search scored models by negative RMSE on the validation folds.</p><pre># Fixed parameters (will not be tuned)<br>fixed_params = dict(<br>    objective=&#39;reg:squarederror&#39;,<br>    eval_metric=&#39;rmse&#39;,<br>    enable_categorical=True,<br>    tree_method=&#39;hist&#39;,<br>    colsample_bytree=0.5,<br>    random_state=42,<br>)<br><br><br># Parameters to tune<br>param_dist = {<br>    &#39;max_depth&#39;: stats.randint(10, 25),<br>    &#39;learning_rate&#39;: stats.uniform(0.01, 0.1),<br>    &#39;subsample&#39;: stats.uniform(0.5, 1),<br>    &#39;n_estimators&#39;: stats.randint(50, 200),<br>    &#39;reg_alpha&#39;: [0, 1, 5],<br>    &#39;reg_lambda&#39;: np.logspace(0, 2, 5),<br>}<br><br># Create the XGBoost model object with default parameters<br>xgb_model = XGBRegressor(**fixed_params)<br><br># Create the RandomizedSearchCV object<br>randomized_search = RandomizedSearchCV(<br>    estimator=xgb_model,<br>    param_distributions=param_dist,<br>    cv=3,<br>    scoring=&#39;neg_root_mean_squared_error&#39;,<br>    verbose=0,<br>    n_jobs=-1,<br>    n_iter=50,<br>)<br><br># Fit the RandomizedSearchCV object to the training data<br>randomized_search.fit(X_train, y_train)<br><br>print(&quot;Best params from CV:&quot;, randomized_search.best_params_)<br>print(&quot;Best CV RMSE:&quot;, -randomized_search.best_score_)</pre><p>After a few minutes, we obtained the best combo:</p><pre>Best params from CV: {&#39;learning_rate&#39;: 0.052754101835854966, &#39;max_depth&#39;: 19, &#39;n_estimators&#39;: 173, &#39;reg_alpha&#39;: 0, &#39;reg_lambda&#39;: 10.0, &#39;subsample&#39;: 0.5314291856867343}  <br>Best CV RMSE: 0.1695148565901082</pre><p>These parameters yielded a cross-validated RMSE of <strong>~0.170</strong> (in log price units) — a slight improvement over the initial ~0.21. The optimal depth (19) was a bit higher than our initial guess, and a slightly lower learning rate (~0.05) worked better with more trees (~173). Interestingly, the search suggested no L1 regularization (α=0) and a stronger L2 (λ≈10), meaning the model favored smoothing weights via ridge penalty rather than pruning entire splits.</p><p><em>Overall, this tuning provided only a modest boost in performance. Our baseline XGBoost was already strong, so RandomizedSearchCV improved the validation RMSE from roughly 0.21 to 0.17 — a noticeable gain but not a dramatic leap. In other words, hyperparameter tuning refined the model’s accuracy but did not revolutionize it, confirming that our initial settings were reasonably well-chosen.</em></p><p>With tuned hyperparameters in hand, we <strong>retrained the model</strong> on the combined training+validation data (90% of all data) to maximize learning before final testing. We set the model with the best parameters and fit it to the full 90% data, without early stopping this time, using the chosen n_estimators=198 (we set n_estimators to 198 for the final model to match the scale of the lowered learning rate, trading off longer training for potentially better performance):</p><pre># Retrain on Train + Val<br>X_fit = pd.concat([X_train, X_val], axis=0)<br>y_fit = pd.concat([y_train, y_val], axis=0)<br><br># Define XGBoost Regressor model<br>model = XGBRegressor(**randomized_search.best_params_, **fixed_params)<br>model.fit(X_fit, y_fit, verbose=False)</pre><h3>Model Performance on Test Data</h3><p>Finally, we evaluated the tuned model on the hold-out <strong>test set</strong> (the 10% of data never seen during training or tuning):</p><pre># Predict on test<br>y_pred_log = model.predict(X_test)<br><br># Metrics on log scale<br>rmse_log = np.sqrt(mean_squared_error(y_test, y_pred_log))<br>r2_log = r2_score(y_test, y_pred_log)<br>mae_log = mean_absolute_error(y_test, y_pred_log)<br><br># Adjusted R²<br>n = X_test.shape[0]  # number of observations<br>p = X_test.shape[1]  # number of predictors<br>adj_r2_log = 1 - (1 - r2_log) * (n - 1) / (n - p - 1)<br><br>print(f&quot;Test RMSE (log scale): {rmse_log:.6f}&quot;)<br>print(f&quot;Test MAE  (log scale): {mae_log:.6f}&quot;)<br>print(f&quot;Test R²   (log scale): {r2_log:.6f}&quot;)<br>print(f&quot;Test Adjusted R² (log scale): {adj_r2_log:.6f}&quot;)<br><br># Metrics in original units<br>y_test_orig = np.expm1(y_test)<br>y_pred_orig = np.expm1(y_pred_log)<br><br>rmse_orig = np.sqrt(mean_squared_error(y_test_orig, y_pred_orig))<br>r2_orig = r2_score(y_test_orig, y_pred_orig)<br>mae_orig = mean_absolute_error(y_test_orig, y_pred_orig)<br>adj_r2_orig = 1 - (1 - r2_orig) * (n - 1) / (n - p - 1)<br><br>print(f&quot;Test RMSE (original units): {rmse_orig:,.4f}&quot;)<br>print(f&quot;Test MAE  (original units): {mae_orig:,.4f}&quot;)<br>print(f&quot;Test R²   (original units): {r2_orig:.6f}&quot;)<br>print(f&quot;Test Adjusted R² (original units): {adj_r2_orig:.6f}&quot;)</pre><ul><li><strong>RMSE (log scale)</strong>: 0.160527</li><li><strong>MAE (log scale)</strong>: 0.094364</li><li><strong>R² (log scale)</strong>: 0.957801</li><li><strong>Adjusted R² (log scale)</strong>: 0.957791</li></ul><p>Converting predictions back to AED currency:</p><ul><li><strong>RMSE</strong>: 447,841.32 AED</li><li><strong>MAE</strong>: 158,213.87 AED</li><li><strong>R²</strong>: 0.948936</li><li><strong>Adjusted R²</strong>: 0.948923</li></ul><p>In other words, our model explains about <strong>94.89%</strong> of the variance in <strong>unseen</strong> property prices in the test set — a strong result. The RMSE indicates that larger errors are possible due to some high-variance cases (not surprising given some properties are worth tens of millions), but the MAE of ~<strong>160k</strong> <strong>AED</strong> shows that, for a typical prediction, the deviation from the actual price is <strong>relatively small</strong>. This suggests that while occasional big misses occur, most predictions are much closer to the true values.</p><p>Given Dubai’s wide range of property values (from a few hundred thousand to tens of millions AED), this is a remarkably tight prediction range. The close match between R² and Adjusted R² further confirms that the model generalizes well and is not overfitting, even with many features in use.</p><h3>Predicted vs. Actual Prices</h3><p>How well did the model’s predictions align with reality? We plot the predicted price vs. actual sale price for test instances:</p><pre>df = pd.DataFrame({&#39;y_test&#39;: y_test.reset_index(drop=True), <br>                   &#39;y_pred&#39;: y_pred_log.round(2), <br>                   &#39;y_test_orig&#39;: y_test_orig.reset_index(drop=True).astype(int),<br>                   &#39;y_pred_orig&#39;: y_pred_orig.round(2).astype(int),<br>                   })</pre><pre>plt.figure(figsize=(6, 6))<br>plt.scatter(df[&#39;y_test&#39;], df[&#39;y_pred&#39;], alpha=0.3)<br>plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], &#39;--r&#39;)<br>plt.xlabel(&quot;Actual Price&quot;)<br>plt.ylabel(&quot;Predicted Price&quot;)<br>plt.title(&quot;Predicted vs Actual Property Worth&quot;)<br>plt.grid(True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*SuHwfauJnGaljny4PnesAw.png" /><figcaption><em>Predicted vs. Actual property prices (in logₑ-AED)</em></figcaption></figure><p><em>Each point is a property sale; the red line is an ideal y=x reference. Predictions tightly cluster around the diagonal, indicating high accuracy. A slight underestimation is seen for the priciest properties (points below the line on the right end), while some cheaper sales are a bit over-predicted (points above the line on left), but these deviations are relatively minor.</em></p><p>The scatter above (on log-transformed scale for visibility) shows most points densely hugging the diagonal — meaning the model’s predicted price is usually very close to the actual price, so the errors balance out without systematic skew.</p><p>Notably, the model is somewhat less accurate in absolute terms for the ultra-high-end properties, but that’s to be expected — for example, <strong>predicting a villa that sells for 50 million AED as 45 million AED is a <em>5 million</em> error, yet only a 10% relative error</strong>. In percentage terms, even the top-end predictions are quite reasonable. Overall, the tight clustering around the $y=x$ line shows the model’s predictions track the actual prices very closely across the board.</p><h3>Residual Analysis</h3><p>Another way to assess performance is by looking at <strong>residuals</strong> (prediction errors). We examined the distribution of residuals on the test set:</p><pre># Test Data Residuals<br>residuals = (df[&#39;y_test&#39;] - df[&#39;y_pred&#39;])<br><br>plt.hist(residuals,bins=50)<br>plt.grid(True)<br>plt.xlabel(&#39;Prediction Error&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.title(&#39;Residuals Distribution&#39;)<br>plt.axvline(color=&#39;r&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*rUhXQZkM3EN4WrjCI27QRw.png" /><figcaption><em>Distribution of prediction errors (residuals) on the test set</em></figcaption></figure><p><em>The errors roughly follow a symmetric bell-shaped curve centered at zero (red line), indicating the model does not consistently over or under predict. There are no extreme outliers or heavy skew, suggesting a well-behaved error profile.</em></p><p>As shown, residuals (in log price terms) cluster tightly around 0. The histogram is approximately normal-shaped, with a mean very close to zero and no long tails — a strong indication our model generalizes well. In other words, it’s not making any systematic mistakes; the errors are mostly random noise. This confirms what the high R² suggested: our features and XGBoost model successfully captured the vast majority of the variance in property prices.</p><h3>Feature Importance</h3><p>To understand what drives our model’s predictions, we examined the <strong>permutation importance</strong> scores for all features. This method measures how much the model’s prediction error increases when a feature’s values are randomly shuffled — features causing a large error increase are deemed more important.</p><p>The <strong>top 10 features</strong> are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*kfzKZRYySJkWsCns6mZQQw.png" /></figure><p><em>Top 10 most influential features according to permutation importance.</em></p><ol><li>🏠 <strong>procedure_area</strong> — Property size is the strongest driver of price. Its influence dwarfs all others.</li><li>🏙️ <strong>master_project_en</strong> — Large-scale developments or master projects boost value through amenities, branding, and exclusivity.</li><li>📆 <strong>year</strong> — The year of sale reflects market cycles, letting the model adjust for inflation, booms, and slowdowns.</li><li>🏗️ <strong>project_name_en</strong> — The specific project name given by developers often reflects reputation and quality.</li><li>🛏️ <strong>rooms_count</strong> — More rooms usually mean higher prices, and the model captures this relationship clearly.</li><li>📍 <strong>area_name_en</strong> — Neighborhood matters: some Dubai areas command significantly higher prices than others.</li><li>🏢 <strong>building_name_en</strong> — The building name captures micro-location prestige and perceived quality.</li><li>📐 <strong>area_per_room</strong> — Average space per room highlights layout efficiency and spaciousness.</li><li>📑 <strong>procedure_name_en</strong> — The sale classification (e.g., type of transaction) adds predictive signal.</li><li>🚇 <strong>nearest_metro_en</strong> — Proximity to metro stations raises value, though less than size or location.</li></ol><p><strong>Overall:</strong> The model’s priorities align closely with real-world valuation principles. <strong>Size, location, and property type dominate</strong>, while timing, branding, and accessibility features provide meaningful refinements.</p><h3>Conclusion and Next Steps</h3><p>Through careful data preparation and modeling, we built a robust <strong>XGBoost model</strong> capable of predicting Dubai property prices with high accuracy (<strong>≈95% R² on unseen data</strong>). The model generalizes well, with balanced errors and sensible feature influences, demonstrating the value of combining <strong>real estate domain knowledge</strong> with machine learning. The result is a model that not only fits the data but also makes intuitive sense.</p><p><strong>Key takeaways:</strong></p><ul><li><strong>Train/test/validation split (80/10/10)</strong> → Ensured honest evaluation and avoided overfitting.</li><li><strong>Log-transform of the target (</strong><strong>actual_worth)</strong> → Stabilized variance and improved model training.</li><li><strong>XGBoost’s </strong><strong>enable_categorical=True</strong> → Handled categorical features natively, avoiding manual encoding.</li><li><strong>Hyperparameter tuning</strong> → Boosted performance, although the baseline model was already strong thanks to robust features.</li><li><strong>Interpretability checks</strong> → Feature importance and residual analysis confirmed the model is capturing real patterns rather than noise.</li></ul><p>In practice, this model could help investors and policymakers estimate property values based on key characteristics and timing of sale. Yet important factors remain missing — such as property condition, waterfront or premium views, sale type (off-plan vs. secondary), developer brand, building age, and proximity to amenities like schools and beaches. These likely exert substantial influence, and incorporating them could further boost accuracy.</p><p>With the available data, the model still performed exceptionally well, explaining over 95% of price variance on the test set. But it remains a proof-of-concept: powerful, yet not fully deployment-ready without richer features and refinements to capture real-world nuances.</p><p><strong>Future directions:</strong></p><ul><li><strong>Time-series framing</strong> — Recast the problem as a true forecast. For example, train on past sales to predict future prices (using a cutoff date for training vs. testing) and update the model continually with new data.</li><li><strong>k-fold cross-validation</strong> — Confirm the model’s stability across different splits of the data. This would ensure our results aren’t dependent on one particular train/test split and help tune the model more reliably.</li><li><strong>Model ensembles</strong> — Combine multiple models (e.g. XGBoost + LightGBM + CatBoost, or DNNs) to push accuracy further. Ensemble approaches could capture complementary patterns and reduce generalization error.</li></ul><p>This concludes our deep dive into Dubai’s real estate data. From exploration and cleaning to feature engineering and modeling, we’ve uncovered the factors that shape property prices and built a predictive framework leveraging them. <strong>Dubai’s real estate story, as told by data, combines location-driven value with temporal market dynamics</strong> — and while we now have a quantifiable, predictive understanding of that story, adding richer property details could make the narrative even sharper.</p><p>*<em>(For those interested in the technical details or wanting to reproduce this analysis, the full code and notebook for this exploration are available on the project’s GitHub repository: </em><a href="https://github.com/ssuljo/dld_transactions_analytics/blob/main/data_preparation.ipynb"><em>https://github.com/ssuljo/dld_transactions_analytics/blob/main/data_preparation.ipynb</em></a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3721334d76d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling Dubai’s Real Estate: A Data-Driven Dive (Part 3)]]></title>
            <link>https://medium.com/@skokhatska/unveiling-dubais-real-estate-a-data-driven-dive-part-3-e2c4e178408d?source=rss-8fcb7662e908------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2c4e178408d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Svitlana Kokhatska]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 07:47:49 GMT</pubDate>
            <atom:updated>2025-09-01T21:25:30.963Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Turning transactions into model-ready features</em></h4><h3>Unveiling Dubai’s Real Estate (Part 3): Engineering Features that Capture Market Dynamics</h3><h4>Transforming clean data into powerful predictors — from encoding existing features to creating custom metrics — ready for machine learning models</h4><h3>Recap and the Road Ahead</h3><p>Before diving into new features, let’s quickly recap our progress. We now have a clean dataset of roughly <strong>906,000</strong> residential sale transactions in Dubai (2004–mid 2025). The data is consistent and mostly complete, providing a solid foundation. In this part, we’ll enhance this dataset through feature engineering. Our goal is to derive additional signals (e.g. extracting <strong>time-based features</strong> from dates) and convert existing fields into more <strong>model-friendly formats</strong>. By the end of this process, our data will be fully prepared for analysis and predictive modeling in the next part.</p><h3>Capturing Time Trends with Date Features</h3><p>One of the most important factors in real estate is <strong>when</strong> a sale took place. Dubai’s property market has evolved significantly between 2004 and 2025, so we want our model to recognize temporal patterns (like market booms or seasonal effects). To achieve this, we convert the transaction date (instance_date) into useful numeric features:</p><pre># Extract date components<br>data_cleaned[&#39;year&#39;] = data_cleaned[&#39;instance_date&#39;].dt.year<br>data_cleaned[&#39;month&#39;] = data_cleaned[&#39;instance_date&#39;].dt.month<br>data_cleaned[&#39;day&#39;] = data_cleaned[&#39;instance_date&#39;].dt.day<br><br># Drop the original date column, since we have extracted its useful <br>s<br>data = data.drop(columns=[&#39;instance_date&#39;])</pre><p>These features allow the model to pick up on <strong>long-term trends (year)</strong> and <strong>seasonal or monthly fluctuations (month/day)</strong> in sale behavior.</p><p>This will prevent the model from mistakenly treating a 2006 sale and a 2021 sale as equivalent. Instead, the model can learn, for example, that <strong>properties sold in recent years generally have higher prices</strong> (due to market appreciation or inflation) compared to those sold a decade prior.</p><p>To better reflect the cyclical nature of calendar dates — like months looping from December to January — we apply <strong>cyclical encoding</strong> using sine and cosine transformations:</p><pre># Cyclical encoding for month and day<br><br>data_cleaned[&#39;month_sin&#39;] = np.sin(2 * np.pi * data_cleaned[&#39;month&#39;] / 12)<br>data_cleaned[&#39;month_cos&#39;] = np.cos(2 * np.pi * data_cleaned[&#39;month&#39;] / 12)<br>data_cleaned[&#39;day_sin&#39;] = np.sin(2 * np.pi * data_cleaned[&#39;day&#39;] / 31)<br>data_cleaned[&#39;day_cos&#39;] = np.cos(2 * np.pi * data_cleaned[&#39;day&#39;] / 31)</pre><p><strong><em>Note</em></strong><em>: While cyclical encoding can be useful, especially for models like linear regression, it has limited impact for tree-based models like XGBoost.</em></p><p>These time-aware features will improve our model’s ability to capture temporal effects like price surges during certain seasons or long-term market appreciation.</p><p>Below is the yearly distribution of transactions</p><pre># Set plot style<br>sns.set_theme(style=&quot;whitegrid&quot;)<br><br># Count number of transactions per year<br>year_counts = data_cleaned[&#39;year&#39;].value_counts().sort_index()<br><br># Plot<br>plt.figure(figsize=(10, 6))<br>ax = sns.barplot(x=year_counts.index, y=year_counts.values, hue=year_counts.index, palette=&#39;viridis&#39;)<br><br># Add bar labels<br>for i, v in enumerate(year_counts.values):<br>    ax.text(i, v + 500, str(v), ha=&#39;center&#39;, fontsize=9)<br><br>plt.title(&#39;Number of Transactions by Year&#39;, fontsize=16)<br>plt.xlabel(&#39;Year&#39;)<br>plt.ylabel(&#39;Transaction Count&#39;)<br>plt.xticks(rotation=45)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*warZ0Bl9-umgDUsTO9ROoQ.png" /><figcaption>Number of residential sales by year (Dubai)</figcaption></figure><p>This bar chart highlights the sharp concentration of transactions in recent years. Sales volumes rose steadily through the 2000s and mid-2010s, then surged dramatically after 2020, peaking in 2024 — despite 2025 still being only halfway through the year.</p><p>This dramatic post-2020 rise coincides with the influx of investors and expatriates during the pandemic era, boosted by Dubai’s visa reforms and lifestyle appeal.</p><h3>Imputing Missing Rooms with XGBoost</h3><p>While most of our features are now complete, one notable gap remains in the rooms_en column (number of rooms). Out of ~906,000 property records, about 621 entries lack this information — a very small fraction (~0.07%). In most practical scenarios, such a small proportion could be safely dropped or imputed using simple techniques (e.g., mode imputation). However, for educational purposes, we’ll take a more advanced approach: using a tree-based machine learning model to <strong>predict</strong> the likely room category for each missing entry.</p><p>Our approach is to perform <strong>model-based imputation</strong> using a machine learning classifier. We train an <strong>XGBoost</strong> model to predict rooms_en from other features like location, property type, size, etc. This way, we use the patterns in the data to infer what the missing room values should be. The steps are:</p><ol><li><strong>Drop the target property:</strong> We need to ensure that the imputation model does not use the actual_worth property for training, otherwise it will artificially reinforce the correlation between the rooms feature and price in the training data. It’s critical to prevent any target leakage.</li><li><strong>Split the data:</strong> Separate the dataset into two subsets — one where rooms_en is known, and one where it is null.</li><li><strong>Train a model:</strong> Use the subset with known room categories to train an XGBoost classifier, treating rooms_en as the target variable and all other features as inputs.</li><li><strong>Validate accuracy:</strong> We set aside a portion of the known data for validation and found the model to be highly accurate (around 96% on the test set), indicating it can predict the room category reliably.</li><li><strong>Impute missing values:</strong> Use the trained model to predict room categories for the 621 records with missing rooms_en.</li><li><strong>Recombine the data:</strong> Merge the imputed results back with the main dataset, so now every transaction has a room category.</li></ol><p>In code, the process looks like this (using a simplified representation):</p><pre># Split the dataset into rows with and without &#39;rooms_en&#39;<br>df_with_rooms = data_cleaned[data_cleaned[&#39;rooms_en&#39;].notna()]<br>df_no_rooms  = data_cleaned[data_cleaned[&#39;rooms_en&#39;].isna()]<br><br># Prepare features (X) and target (y) for modeling<br>from sklearn.preprocessing import LabelEncoder<br>le = LabelEncoder()<br>y = le.fit_transform(df_with_rooms[&#39;rooms_en&#39;])     # encode room labels as numeric classes<br>X = df_with_rooms.drop([&#39;rooms_en&#39;,&#39;actual_worth&#39;], axis=1)<br><br># Train XGBoost classifier on known room categories<br>from xgboost import XGBClassifier<br>model = XGBClassifier(objective=&#39;multi:softmax&#39;, num_class=len(le.classes_),<br>                      enable_categorical=True, n_estimators=45, max_depth=25,<br>                      reg_alpha=2, reg_lambda=5, n_jobs=-1)<br>model.fit(X, y)<br># Predict missing &#39;rooms_en&#39; values<br>y_pred_encoded = model.predict(df_no_rooms.drop(&#39;rooms_en&#39;, axis=1))<br>y_pred_labels  = le.inverse_transform(y_pred_encoded)  # convert back to original labels<br># Insert the imputed room labels and recombine the data<br>df_no_rooms[&#39;rooms_en&#39;] = y_pred_labels<br>df_final = pd.concat([df_with_rooms, df_no_rooms])</pre><p>After this imputation step, <strong>all</strong> properties in our dataset have a valid rooms_en value. By using XGBoost to infer the missing rooms, we mitigate potential bias from simply dropping those records or filling a generic value. Essentially, the model learned from the hundreds of thousands of complete cases to predict what the missing ones should likely be. This approach helps preserve data and maintain accuracy — an important consideration in real estate data, where property size/rooms are a key predictor of price.</p><p>With the missing entries filled, we can proceed to make the rooms_en feature more useful for modeling.</p><h3>Numeric Representation of “Rooms” Feature</h3><p>Next, we tackle the <strong>number of rooms</strong> in the property (rooms_en). In the raw data, this feature is stored as a text label. For modeling, it’s more useful to have this as a numeric feature. We also need to handle non-numeric entries like “studio”, “single room” and “penthouse”.</p><p>First, let’s understand the values. We can examine the median sale price (actual_worth) for each category of rooms_en to get a sense of how they compare:</p><pre># Group by &#39;rooms_en&#39; and calculate median &#39;actual_worth&#39;, sorted<br>median_worth = df_final.groupby(&#39;rooms_en&#39;)[&#39;actual_worth&#39;].median().sort_values()<br><br># Plot horizontal bar chart<br>plt.figure(figsize=(8, 5))<br>sns.barplot(<br>    x=median_worth.values,<br>    y=median_worth.index,<br>    hue=median_worth.values,<br>    palette=&#39;viridis&#39;, <br>    legend=False<br>)<br><br># Add AED value labels<br>for i, (value, label) in enumerate(zip(median_worth.values, median_worth.index)):<br>    plt.text(value, i, f&quot;AED {value:,.0f}&quot;, va=&#39;baseline&#39;)<br><br>plt.title(&#39;Median Actual Worth by Number of Rooms&#39;)<br>plt.xlabel(&#39;Median Actual Worth&#39;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*41ix4aSKdUwjGZbkLHVyWQ.png" /></figure><p>Based on the chart above, we’ll map <strong>“single_room”</strong> to 0<strong> (</strong>since its median price was lowest),<strong> “studio”</strong> to 0.5, and <strong>&quot;penthouse&quot;</strong> to 4.5, while converting all other room types to integers. This approach treats the number of rooms as an <strong>ordinal numeric feature</strong>, preserving the natural ordering. It helps the model learn that <strong>more rooms typically correlate with higher prices</strong>.</p><p>We can define a mapping like this:</p><pre># Convert room counts from text to numeric<br>room_mapping = {<br>    &#39;single_room&#39;: 0,   # treated as smaller than studio<br>    &#39;studio&#39;: 0.5,<br>    &#39;1_bedroom&#39;: 1,<br>    &#39;2_bedroom&#39;: 2,<br>    &#39;3_bedroom&#39;: 3,<br>    &#39;4_bedroom&#39;: 4,<br>    &#39;penthouse&#39;: 4.5,   # between 4 and 5<br>    &#39;5_bedroom&#39;: 5,<br>    &#39;6_bedroom&#39;: 6,<br>    &#39;7_bedroom&#39;: 7,<br>    &#39;8_bedroom&#39;: 8<br>}<br>df_final[&#39;rooms_en&#39;] = df_final[&#39;rooms_en&#39;].map(room_mapping)<br><br># Rename the column for clarity<br>df_final = df_final.rename(columns={&#39;rooms_en&#39;: &#39;rooms_count&#39;})</pre><p>Now rooms_count is a quantitative feature that the model can interpret.</p><h3>Deriving the ‘Area per Room’ Feature</h3><p>Another valuable feature we can engineer is the <strong>area per room</strong>, which captures how spacious each room is in a given property. It’s a useful proxy for property comfort, quality, and possibly even luxury. A large villa and a cramped flat may have the same number of rooms — but the <strong>area per room</strong> will highlight the difference. A higher area_per_room indicates more spacious rooms (on average), a proxy for property luxury or comfort.</p><p>We can compute this feature by dividing the total procedure_area by the number of rooms:</p><pre># Calculate area per room, handling division by zero or missing values<br>df_final[&#39;area_per_room&#39;] = df_final.apply(<br>    lambda row: row[&#39;procedure_area&#39;] / row[&#39;rooms_count&#39;] if row[&#39;rooms_count&#39;] &gt;= 1 else row[&#39;procedure_area&#39;],<br>    axis=1<br>)</pre><p>This ensures that for <strong>studio flats or one-room units</strong>, we don’t divide by zero — instead, we default to using the full area as the per-room value. This engineered feature can help the model learn price differences based on room size and density.</p><h3>Encoding Categorical Variables for Modeling</h3><p>Our dataset includes several categorical features that are currently represented as text. Most traditional machine learning models can’t handle raw text labels directly — these need to be converted into numerical form. However, it’s important to encode them <strong>without introducing any artificial order or bias</strong>, especially for nominal categories (like community names or property types, which don’t have an inherent rank order). <em>For example, we wouldn’t want the model to think area ‘Downtown’ &gt; ‘Marina’ &gt; ‘JLT’ just because we label-encoded them as 3 &gt; 2 &gt; 1.</em></p><p>Since we’re going to use <strong>XGBoost Regressor</strong> in the next stage, we can take advantage of its built-in support for categorical features. XGBoost can handle categorical data <strong>natively</strong>, without requiring manual encoding. All we need to do is <strong>explicitly set the column’s data type to</strong> category, and XGBoost will take care of the rest:</p><pre>categorical_cols = df_final.select_dtypes(include=[&#39;object&#39;]).columns<br>df_final[categorical_cols] = df_final[categorical_cols].astype(&quot;category&quot;)</pre><p>By doing this, we let the XGBoost model know which features are categorical. Internally, it will treat the different categories appropriately (without assuming any numeric relationship between them), which simplifies our preprocessing workflow.</p><h3>Conclusion and Next Steps</h3><p>By performing feature engineering, we’ve <strong>unveiled new dimensions in the data</strong> that were not explicit in the raw form. We’ve ensured our model will know the difference between a villa sold in 2022 and a flat sold in 2010, or a studio versus a three-bedroom. Each engineered feature was motivated by domain knowledge or data intuition, and we took care to do this in a way that avoids data leakage.</p><p>With a solid feature set now in hand, we’re ready to move to the exciting part — modeling. In <strong>Part 4</strong>, we’ll feed these engineered features into machine learning models to <strong>predict property prices</strong>. We’ll explore how well our features perform, identify which ones are most influential, and fine-tune our models for the best predictive power. Stay tuned as we transition from data preparation to model building, continuing our data-driven dive into Dubai’s real estate landscape!</p><p>*<em>(For those interested in the technical details or wanting to reproduce this analysis, the full code and notebook for this exploration are available on the project’s GitHub repository: </em><a href="https://github.com/ssuljo/dld_transactions_analytics/blob/main/data_preparation.ipynb"><em>https://github.com/ssuljo/dld_transactions_analytics/blob/main/data_preparation.ipynb</em></a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2c4e178408d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling Dubai’s Real Estate: A Data-Driven Dive (Part 2)]]></title>
            <link>https://medium.com/@skokhatska/unveiling-dubais-real-estate-a-data-driven-dive-part-2-6a65d681cd71?source=rss-8fcb7662e908------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a65d681cd71</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[real-estate]]></category>
            <dc:creator><![CDATA[Svitlana Kokhatska]]></dc:creator>
            <pubDate>Thu, 14 Aug 2025 18:54:50 GMT</pubDate>
            <atom:updated>2025-09-01T21:20:00.601Z</atom:updated>
            <content:encoded><![CDATA[<h4>Stripping noise to reveal the signal in Dubai’s property market</h4><h3>Unveiling Dubai’s Real Estate (Part 2): Cleaning &amp; Refining Data for Accurate Market Insights</h3><h4>From filtering core residential sales to handling missing values and outliers — building a solid, analysis-ready foundation</h4><h3>Recap and the Road Ahead</h3><p>In <a href="https://medium.com/@skokhatska/unveiling-dubais-real-estate-a-data-driven-dive-part-1-dfca41c5d1a6">Part 1</a>, we explored Dubai’s real estate market, uncovering trends, patterns, and initial insights from millions of property transactions. Now, in Part 2, we turn our attention to cleaning and refining that data — filtering to core residential sales, systematically handling missing values, and addressing outliers to ensure accuracy and consistency. This clean, analysis-ready dataset will serve as the solid foundation for <a href="https://medium.com/@skokhatska/unveiling-dubais-real-estate-a-data-driven-dive-part-3-e2c4e178408d">Part 3</a>, where we’ll engineer powerful features to capture location, property characteristics, and temporal trends, setting the stage for Part 4’s predictive modeling with XGBoost.</p><h3>Filtering and Trimming the Dataset</h3><p>Before diving into modeling, we need to isolate the <strong>residential sale transactions</strong> that truly reflect market prices. In <a href="https://medium.com/@skokhatska/unveiling-dubais-real-estate-a-data-driven-dive-part-1-dfca41c5d1a6">Part 1</a>, we saw that sales made up the majority of the data, while mortgages and gift transfers (often recorded at nominal values) formed smaller segments. To focus our analysis, we perform several filtering steps:</p><ul><li><strong>Keep only sales:</strong> We exclude <strong>gift</strong> and <strong>mortgage</strong> records entirely. Gifts (about 3.7% of entries) do not represent arm’s-length sales, and mortgages (about 20%) are loan registrations rather than purchase prices.</li><li><strong>Focus on residential properties:</strong> We filter out commercial property deals. <a href="https://medium.com/@skokhatska/unveiling-dubais-real-estate-a-data-driven-dive-part-1-dfca41c5d1a6">Part 1</a>’s exploration showed a long tail of property types beyond residential units. Here we retain only the primary residential categories — <strong>flats, villas, townhouses</strong> — as well as <strong>hotel apartments/rooms</strong> (which we’ll treat similarly to residential units). This removes ~23% of records and ensures our analysis centers on the housing market.</li><li><strong>Drop redundant columns:</strong> The dataset comes with many identifier or duplicate fields (IDs, Arabic name duplicates, etc.) that aren’t useful for analysis. We drop these to streamline the data.</li></ul><p>The code below implements these steps:</p><pre># Drop Arabic columns and low-information ID fields<br>columns_to_drop = df.columns[<br>    df.columns.str.endswith((&#39;_ar&#39;, &#39;_id&#39;))<br>].tolist() + [<br>    &#39;project_number&#39;,       # project ID<br>    &#39;no_of_parties_role_1&#39;, # irrelevant<br>    &#39;no_of_parties_role_2&#39;, # irrelevant<br>    &#39;no_of_parties_role_3&#39;, # irrelevant<br>    &#39;property_type_en&#39;,     # redundant — sub-type is more descriptive<br>]<br><br>data = df.drop(columns=columns_to_drop).copy()<br><br># Filter to sale transactions only<br>data = data[data[&#39;trans_group_en&#39;] == &#39;Sales&#39;]<br><br># Filter to key property sub-types (residential &amp; closely related)<br>allowed_subtypes = [&#39;flat&#39;, &#39;villa&#39;, &#39;stacked_townhouses&#39;, &#39;hotel_apartment&#39;, &#39;hotel_rooms&#39;]<br>data = data[data[&#39;property_sub_type_en&#39;].isin(allowed_subtypes)]<br><br># Remove any lingering non-residential entries misclassified in rooms_en<br>data = data[~data[&#39;rooms_en&#39;].isin([&#39;office&#39;, &#39;shop&#39;])]<br>print(&quot;Shape after filtering:&quot;, data.shape)<br>print(data[&#39;property_sub_type_en&#39;].value_counts())</pre><p>In the code above, we first drop columns like IDs and Arabic names that we won’t need. We then filter trans_group_en to “Sales” only, and constrain property_sub_type_en to a list of residential categories. A small additional check on the rooms_en field helps remove any record that might have slipped through (e.g. a few entries labeled as “office” or “shop” in the rooms field, this eliminates only a handful of records). After these steps, the dataset shrinks in size.</p><pre>Shape after filtering: (909119, 20)<br>property_sub_type_en<br>flat                  776404<br>villa                  95836<br>hotel_apartment        23385<br>hotel_rooms            13145<br>stacked_townhouses       349</pre><p><strong>Result:</strong> We now have a clean subset of <strong>residential sale transactions </strong>(with roughly <strong>909,000 records of property sales</strong> in Dubai’s housing market). This includes mostly apartment flats (by far the largest category) and villas, plus a smaller number of townhouse units and hotel apartment sales. The dominance of flats and villas aligns with the initial data profile — our analysis will be largely driven by these housing unit transactions.</p><h3>Handling Missing Data</h3><p>With the irrelevant records out of the way, we turn to the quality of the remaining data. A critical step is understanding and addressing <strong>missing values</strong> in each feature. Some fields in this dataset are sparsely populated or not applicable to most transactions.</p><p>In the first part we figured out that a handful of features have significant portions missing. Our strategy is to <strong>drop the columns that are mostly empty or not useful, and leave the rest for now</strong> (we’ll consider imputation or encoding later if needed):</p><ul><li>We drop rent_value and meter_rent_price entirely. With ~97% missing values, these columns don’t contribute much information for the bulk of sales.</li><li>Other columns with moderate missingness (like project name, nearest landmark/metro/mall, ~17–26% missing) we <strong>retain</strong> for now since they could still hold useful information about location influence on price.</li></ul><p>Implementing these drops:</p><pre># Drop columns with excessive missing or redundant info<br>cols_to_drop = [<br>    &#39;rent_value&#39;,        # ~96% missing<br>    &#39;meter_rent_price&#39;,  # ~96% missing<br>]<br>data = data.drop(columns=cols_to_drop)</pre><p>After dropping these columns, we have pared down the dataset to the essential features: transaction details (date, type), property characteristics (subtype, area, rooms, parking, etc.), location (community area and master project, plus nearest landmark/metro/mall), and the target variable we care about (the sale price, actual_worth). We’ll circle back to the moderate missing values later if they pose an issue, but for now our dataset is much cleaner in terms of completeness.</p><h3>Addressing Outliers</h3><p>Even with the right records and fields in place, raw real estate data often contains <strong>extreme values</strong> that can skew analysis. In <a href="https://medium.com/@skokhatska/unveiling-dubais-real-estate-a-data-driven-dive-part-1-dfca41c5d1a6">Part 1</a>’s initial profiling, we noticed very wide ranges for price and area — for example, some recorded sales had <em>areas under 0.01 m² or prices over AED 13 billion</em>, which are almost certainly data errors or extraordinary cases. These outliers can wildly distort statistics and models, so we need to handle them.</p><p>First, let’s get a sense of how skewed the key numeric distributions are. We examine the <strong>sale price (</strong><strong>actual_worth)</strong> and <strong>property size (</strong><strong>procedure_area)</strong> distributions (using a log scale to tame the extreme tail):</p><pre># Examine distribution of price and area on log scale<br>data_log = data.copy()<br>data_log[&#39;actual_worth&#39;] = np.log10(data_log[&#39;actual_worth&#39;] + 1)<br>data_log[&#39;procedure_area&#39;] = np.log10(data_log[&#39;procedure_area&#39;] + 1)<br><br># Plot histograms and get axes<br>axes = data_log[[&#39;actual_worth&#39;, &#39;procedure_area&#39;]].hist(<br>    bins=50, figsize=(12, 6), layout=(1, 2)<br>)<br><br># Add titles and axis labels<br>plt.suptitle(&quot;Log-Scaled Distributions&quot;, fontsize=16)<br><br>axes = axes.flatten()<br>axes[0].set_xlabel(&quot;Log10 of Actual Worth&quot;)<br>axes[0].set_ylabel(&quot;Frequency&quot;)<br>axes[1].set_xlabel(&quot;Log10 of Procedure Area&quot;)<br><br>plt.tight_layout(rect=[0, 0.03, 1, 0.95])  # Adjust layout to fit suptitle<br>plt.show()plt.figure(figsize=(12,4))<br>plt.subplot(1,2,1)<br>plt.hist(np.log10(data[&#39;actual_worth&#39;] + 1), bins=50, color=&#39;steelblue&#39;)<br>plt.xlabel(&#39;Log10 of Sale Price (AED)&#39;)<br>plt.ylabel(&#39;Frequency&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QUM3cyNgBy_COhfCpOsXvg.png" /><figcaption>Distribution of Prices and Areas (log scale) before cleanup</figcaption></figure><p><strong><em>Observation</em></strong><em>: The log-scaled histograms show that while most properties cluster in a reasonable range, </em><strong><em>there are long tails on the left and right</em></strong><em>. In other words, </em><strong><em>a few properties are extremely large/small or extremely expensive/cheap</em></strong><em>, far beyond the bulk of transactions.</em></p><p>To formally identify outliers, we use a <strong>quantile-based approach</strong>. Instead of simple rules like “&gt;3 standard deviations” (which don’t work well with heavy skew), we’ll use very high/low percentile cut-offs:</p><ul><li>For property size (procedure_area), define “extremely large” as above the <strong>99.9th percentile</strong>, and “implausibly small” as below the <strong>0.1th percentile</strong>.</li><li>For price-per-square-meter (meter_sale_price), define extremely high and low in a similar way: above the <strong>99.9th percentile</strong> and below the <strong>0.1th percentile</strong>.</li></ul><p>We apply these thresholds and count how many records fall outside:</p><pre># Determine outlier thresholds<br>high_area_thr = data[&#39;procedure_area&#39;].quantile(0.999)<br>low_area_thr = data[&#39;procedure_area&#39;].quantile(0.001)<br>high_price_thr = data[&#39;meter_sale_price&#39;].quantile(0.999)<br>low_price_thr = data[&#39;meter_sale_price&#39;].quantile(0.001)</pre><pre># Identify outlier records<br>large_area_idx = data[data[&#39;procedure_area&#39;] &gt; high_area_thr].index<br>tiny_area_idx  = data[data[&#39;procedure_area&#39;] &lt; low_area_thr].index<br>high_price_idx = data[data[&#39;meter_sale_price&#39;] &gt; high_price_thr].index<br>low_price_idx  = data[data[&#39;meter_sale_price&#39;] &lt; low_price_thr].index<br>print(f&quot;{len(large_area_idx)} records with area &gt; {high_area_thr:.2f} m²&quot;)<br>print(f&quot;{len(tiny_area_idx)} records with area &lt; {low_area_thr:.2f} m²&quot;)<br>print(f&quot;{len(low_price_idx)} records with price/m² &lt; {low_price_thr:.2f} AED&quot;)<br>print(f&quot;{len(high_price_idx)} records with price/m² &gt; {high_price_thr:.2f} AED&quot;)</pre><pre>910 records with area &gt; 971.51 m²<br>908 records with area &lt; 7.86 m²<br>910 records with price/m² &lt; 1247.35 AED<br>910 records with price/m² &gt; 90991.89 AED</pre><p>Running this code, we find a small set of extreme outliers in each category:</p><ul><li><strong>910 properties</strong> with extraordinarily large area (above ~972 m², i.e. the top 0.1%) — these could be large land plots or data errors.</li><li><strong>908 properties</strong> with implausibly small area (below 7.86 m²). Many of these are likely data entry mistakes (e.g. missing a zero or unit issues) because 7.86 m² is smaller than a typical studio room.</li><li><strong>910 transactions</strong> with extremely low price per square meter (below ~1247.35 AED/m²). Some of these might overlap with the large-area cases (a huge land sold cheaply will have a very low AED/m² value), or they could be heavily discounted sales.</li><li><strong>910 transactions</strong> with extremely high price per square meter (above ~91k AED/m²!). These are almost certainly data errors or very special cases.</li></ul><p>Rather than try to cap or impute these wild values, we opt to <strong>remove these outlier records</strong> altogether. They account for a very small fraction of the data (~<strong>0.26%</strong> of records in total), so dropping them won’t affect our overall analysis or modeling power, but it will make our statistics much more robust.</p><pre># Drop all identified outliers<br>outlier_indices = large_area_idx.union(tiny_area_idx).union(low_price_idx).union(high_price_idx)<br>print(f&quot;Total outlier records to drop: {len(outlier_indices)}&quot;)<br>data = data.drop(index=outlier_indices).reset_index(drop=True)</pre><pre>Total outlier records to drop: 3947</pre><p>By removing these outliers, we eliminate the most egregious anomalies — e.g. properties listed with near-zero size or exorbitant price rates. This leaves us with a dataset that better reflects the typical market range.</p><pre>data_log = new_data.copy()<br>data_log[&#39;actual_worth&#39;] = np.log10(data_log[&#39;actual_worth&#39;] + 1)<br>data_log[&#39;procedure_area&#39;] = np.log10(data_log[&#39;procedure_area&#39;] + 1)<br><br># Plot histograms and get axes<br>axes = data_log[[&#39;actual_worth&#39;, &#39;procedure_area&#39;]].hist(<br>    bins=50, figsize=(12, 6), layout=(1, 2)<br>)<br><br># Add titles and axis labels<br>plt.suptitle(&quot;Log-Scaled Distributions&quot;, fontsize=16)<br><br>axes = axes.flatten()<br>axes[0].set_xlabel(&quot;Log10 of Actual Worth&quot;)<br>axes[0].set_ylabel(&quot;Frequency&quot;)<br>axes[1].set_xlabel(&quot;Log10 of Procedure Area&quot;)<br><br>plt.tight_layout(rect=[0, 0.03, 1, 0.95])  # Adjust layout to fit suptitle<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkSipQq-_G2JAmb6QnkR4g.png" /><figcaption>Distribution of Prices and Areas (log scale) after cleanup</figcaption></figure><p><strong><em>Observation:</em></strong></p><ul><li><em>The distributions have smoother, more symmetrical bell-shaped curves.</em></li><li><em>The long tails are significantly reduced, confirming removal of extreme low/high anomalies.</em></li><li><em>This results in a dataset that is more statistically robust, with values more centered around realistic ranges.</em></li></ul><p>Next, we check area vs. price relationship after the data cleanup.</p><h3>Relationship Between Property Area and Value</h3><pre>plt.figure(figsize=(10, 6))<br>sns.scatterplot(<br>    data=new_data,<br>    x=&#39;procedure_area&#39;,<br>    y=&#39;actual_worth&#39;,<br>    alpha=0.7,<br>    edgecolor=&#39;w&#39;,<br>    s=60<br>)<br><br>plt.title(&#39;Actual Worth by Procedure Area&#39;, fontsize=14)<br>plt.xlabel(&#39;Procedure Area&#39;, fontsize=12)<br>plt.ylabel(&#39;Actual Worth&#39;, fontsize=12)<br>plt.xticks(rotation=45, ha=&#39;right&#39;)<br>plt.tight_layout()<br>plt.grid(True, linestyle=&#39;--&#39;, alpha=0.3)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*y-s822iT_HtuzlGV7TDZfQ.png" /></figure><p><strong><em>Observation:</em></strong><em> The scatter plot above shows that there’s a general upward trend — larger properties tend to have higher values. However, the spread widens significantly for bigger areas, indicating that beyond a certain size, price differences are heavily influenced by other factors such as location, amenities, or property type. The presence of high-value outliers in both small and large areas suggests that area alone is not a perfect predictor of worth.</em></p><p>This confirms that <strong>size alone doesn’t dictate price</strong>, so in <a href="https://medium.com/@skokhatska/unveiling-dubais-real-estate-a-data-driven-dive-part-3-e2c4e178408d">Part 3</a> we will incorporate more features to capture those effects.</p><h3>Fixing Data Types and Consistency</h3><p>The last step in our cleaning process is to ensure all data is in the proper format and standardized form. Two main tasks here are:</p><ul><li><strong>Convert dates to datetime:</strong> The instance_date field (registration date of the transaction) is read as a string. We convert it to a proper datetime object so we can easily extract components like year or month later, or sort by date.</li><li><strong>Standardize categorical text:</strong> We convert all text to a snake case format. This uniform formatting will help avoid treating &quot;Al Barsha South Fourth&quot; and &quot;al barsha south fourth&quot; as distinct categories due to case or spacing differences. It also makes downstream processing easier.</li></ul><p>Let’s perform these fixes:</p><pre># Convert instance_date from string to datetime<br>data[&#39;instance_date&#39;] = pd.to_datetime(data[&#39;instance_date&#39;], format=&#39;%d-%m-%Y&#39;, errors=&#39;coerce&#39;)<br>data = data.dropna(subset=[&#39;instance_date&#39;])  # drop if any invalid dates (if errors=&#39;coerce&#39; produced NaT)</pre><pre># Normalize text columns: strip spaces, lowercase, replace internal spaces with underscores<br>obj_cols = data.select_dtypes(include=&#39;object&#39;).columns<br>data[obj_cols] = data[obj_cols].apply(lambda col: col.str.strip().str.lower().str.replace(&#39; &#39;, &#39;_&#39;))</pre><h3>Final Cleaned Dataset Summary</h3><p>At this point, we have a <strong>cleaned and filtered dataset</strong> ready for exploration and modeling. Let’s recap what we have:</p><ul><li><strong>Scope:</strong> Only <strong>residential sale transactions</strong> in Dubai (sales of flats, villas, townhouses, etc.), from 2004 up through mid-2025.</li><li><strong>Size:</strong> Approximately <strong>906,000 records</strong> (down from 1.5M) after removing non-sale entries, non-residential properties, and extreme outliers.</li><li><strong>Transaction details:</strong> transaction date (instance_date), sale type (procedure_name_en – e.g. sell vs. pre-registration sale).</li><li><strong>Property characteristics:</strong> property subtype (property_sub_type_en – flat, villa, etc.), usage (property_usage_en – nearly all “residential” in this subset), registration type (reg_type_en – whether off-plan or existing), number of rooms (rooms_en), and parking flag (has_parking).</li><li><strong>Location info:</strong> community area name (area_name_en), master development name (master_project_en), nearest landmark/metro/mall (nearest_landmark_en, nearest_metro_en, nearest_mall_en), project and building name given by developer (project_name_en, building_name_en).</li><li><strong>Size and price:</strong> property area in square meters (procedure_area) and the sale price (actual_worth in AED). (We have dropped the derived price-per-m² to avoid redundancy.)</li><li><strong>Missing data:</strong> Other than the location fields which have ~10–20% missing (kept for now), most features are nearly complete. The few missing rooms_en entries can be handled easily if needed.</li><li><strong>Features retained:</strong></li></ul><pre>print(data.shape)<br>data.info()</pre><p>Running this would show the dataset information:</p><pre> #   Column                Non-Null Count   Dtype         <br>---  ------                --------------   -----         <br> 0   trans_group_en        905900 non-null  object        <br> 1   procedure_name_en     905900 non-null  object        <br> 2   instance_date         905900 non-null  datetime64[ns]<br> 3   property_sub_type_en  905900 non-null  object        <br> 4   property_usage_en     905900 non-null  object        <br> 5   reg_type_en           905900 non-null  object        <br> 6   area_name_en          905900 non-null  object        <br> 7   building_name_en      810793 non-null  object        <br> 8   project_name_en       739254 non-null  object        <br> 9   master_project_en     820768 non-null  object        <br> 10  nearest_landmark_en   745558 non-null  object        <br> 11  nearest_metro_en      668679 non-null  object        <br> 12  nearest_mall_en       665163 non-null  object        <br> 13  rooms_en              905279 non-null  object        <br> 14  has_parking           905900 non-null  int64         <br> 15  procedure_area        905900 non-null  float64       <br> 16  actual_worth          905900 non-null  float64</pre><p>The key point is that our dataset is now <strong>well-structured, mostly complete, and free of obvious errors or irrelevant data</strong>.</p><h3>Conclusion and Next Steps</h3><p>Having a clean dataset is crucial before we move on, because any analysis or model we build will only be as good as the data we feed it. Now that we’ve filtered out noise and fixed issues, we can proceed with confidence.</p><p>In <a href="https://medium.com/@skokhatska/unveiling-dubais-real-estate-a-data-driven-dive-part-3-e2c4e178408d"><strong>Part 3</strong></a>, we’ll tackle feature engineering on this polished data — (like deriving new features, mapping existing etc.). With our solid foundation from Part 2, we’re ready to unveil deeper insights into Dubai’s real estate landscape!</p><p>*<em>(For those interested in the technical details or wanting to reproduce this analysis, the full code and notebook for this exploration are available on the project’s GitHub repository: </em><a href="https://github.com/ssuljo/dld_transactions_analytics/blob/main/data_preparation.ipynb"><em>https://github.com/ssuljo/dld_transactions_analytics/blob/main/data_preparation.ipynb</em></a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a65d681cd71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling Dubai’s Real Estate (Part 1): Exploring 1.5M Transactions Across Two Decades]]></title>
            <link>https://medium.com/@skokhatska/unveiling-dubais-real-estate-a-data-driven-dive-part-1-dfca41c5d1a6?source=rss-8fcb7662e908------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfca41c5d1a6</guid>
            <category><![CDATA[real-estate]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Svitlana Kokhatska]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 18:38:57 GMT</pubDate>
            <atom:updated>2025-09-01T21:23:47.483Z</atom:updated>
            <content:encoded><![CDATA[<h4>What can <strong>1.51 million</strong> real estate deals reveal?</h4><h4><em>Launching a multi-part data series to uncover the patterns shaping </em>one of the world’s most dynamic housing markets.</h4><h3>Introduction</h3><p>In this project, we aim to analyse and predict housing prices in Dubai using an extensive dataset of real estate transactions. The data contains over <strong>1.51 million</strong> property transactions recorded by the Dubai Land Department, covering a period from <strong>2004</strong> up to mid-<strong>2025</strong>. Each record includes various attributes such as property type, subtype, location, sale registration date, price, size, and more.</p><p>Before building any predictive models, it’s crucial to perform data profiling and initial exploration to understand the dataset’s structure, identify key patterns, and uncover potential issues (like missing values or outliers) that need to be addressed. In this first part, we walk through loading the data and exploring its main characteristics.</p><h3>Dataset Overview</h3><p>The raw data is provided as a CSV file (Transactions.csv), published by <a href="https://www.dubaipulse.gov.ae/organisation/dld">Dubai Land Department (DLD)</a> and available through the Dubai Pulse open data platform (<a href="https://www.dubaipulse.gov.ae/data/dld-transactions/dld_transactions-open">link</a>). First, let’s load the dataset:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import missingno as msno<br><br># Load the dataset<br>df = pd.read_csv(&#39;Transactions.csv&#39;)<br>print(&quot;Shape:&quot;, df.shape)<br>print(df.head(3))<br>df.info()  # overview of columns and non-null counts</pre><p>Running this shows that the dataset has <strong>1,512,843 rows</strong> and <strong>46 columns</strong>. The features info is below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7772d165f4e64c5f26d9fefc6581372f/href">https://medium.com/media/7772d165f4e64c5f26d9fefc6581372f/href</a></iframe><p>From this initial overview, a few quick facts stand out:</p><ul><li><strong>Transaction Date Range:</strong> The earliest transactions date back to 2003, and the latest are in 2025. The data is not uniformly distributed over time — there are far more transactions in recent years (a point we explore below).</li><li><strong>Transaction Types:</strong> There are three high-level transaction groups (trans_group_en) : <strong>Sales</strong>, <strong>Mortgages</strong>, and <strong>Gifts</strong>.</li><li><strong>Property Types:</strong> The main property types include <strong>land, building, villa, </strong>and<strong> unit</strong>. These are further broken down into sub-types (apartment flats, villas, offices, shops, etc.).</li><li><strong>Missing Data:</strong> Several fields (like building_name_en, project_name_en, rent_value) have substantial missing data.</li></ul><p>With the dataset loaded, let’s explore its characteristics. We’ll start by looking at categorical features to see the composition of transactions.</p><h3>Exploratory Analysis of Categorical Features</h3><p>Now, we examine some key categorical features to understand the distribution of transaction types, property subtypes, and locations in the data.</p><h4>1. Transaction Category Distribution</h4><p>The <strong>trans_group_en</strong> field indicates whether a record is a sale, mortgage, or gift. Let’s see how many transactions fall into each category:</p><pre>ax = sns.countplot(data=df, x=&#39;trans_group_en&#39;, <br>                   order=df[&#39;trans_group_en&#39;].value_counts().index,<br>                   palette=&#39;husl&#39;,<br>                   hue=&#39;trans_group_en&#39;)<br><br>total = len(df)<br>for container in ax.containers:<br>    labels = [f&#39;{(v.get_height() / total * 100):.1f}%&#39; for v in container]<br>    ax.bar_label(container, labels=labels)<br><br>ax.set_xlabel(&#39;Transaction Group&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*Z1verCy2W1ie2jjw2aK0vQ.png" /></figure><p><strong><em>Observation</em></strong><em>: The dominance of sales suggests that our price modeling will primarily learn from sale transactions. Mortgages might not directly factor into a pricing model (they often represent loan registrations), and gift transactions may not reflect market value at all (often listed at nominal or zero price). In a later stage, we might exclude or separately handle these non-sale records, but for now we simply note their presence.</em></p><h4>2. Transaction Type Distribution</h4><p>The procedure_name_en field describes the type of transaction recorded — whether it&#39;s a standard sale, a pre-registration, or a mortgage-related event.<br> To identify the most common transaction types in the market, we counted their frequencies and visualized the <strong>top 15</strong> by number of transactions:</p><pre># Count transactions per transaction type<br>transaction_type_counts = data[&#39;procedure_name_en&#39;].value_counts().head(15)  # Top 15 transaction types<br><br># Set plot style<br>plt.figure(figsize=(10, 8))<br>sns.set_theme(style=&quot;whitegrid&quot;)<br>ax = sns.barplot(<br>    x=transaction_type_counts.values, <br>    y=transaction_type_counts.index, <br>    palette=&quot;Greens_d&quot;,<br>    hue=transaction_type_counts.index<br>)<br><br># Add bar labels<br>for container in ax.containers: # annotate bars with count<br>    ax.bar_label(container,fmt=&#39;%d&#39;, label_type=&#39;edge&#39;, padding=3)  <br><br>plt.title(&quot;Top 15 Transaction Types by Number of Transactions&quot;, fontsize=14)<br>plt.xlabel(&quot;Number of Transactions&quot;)<br>plt.ylabel(&quot;Transaction Type&quot;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*3pZt-L_R0Iqk3ORJ0DPRjQ.png" /></figure><p><strong><em>Observation:</em></strong><em> Sale transactions clearly dominate the dataset. Together, Pre-registration sales and Standard sales make up over </em><strong><em>945,885 records</em></strong><em>, far surpassing all other transaction types. In contrast, mortgage-related entries appear far less frequently and are often tied to purchases indirectly. Since our goal is to model transaction prices based on property features, we will focus primarily on these </em><strong><em>direct sale records</em></strong><em>, which offer the most reliable and interpretable signals for price analysis.</em></p><h4>3. Geographical Distribution</h4><p>Each record has an area/community name, specifying where the property is located. The data spans all of Dubai’s neighborhoods. To get a sense of the top locations, we counted transactions per area (using master_project_en property) and plotted the top 20 areas by number of transactions:</p><pre># Count transactions per area<br>area_counts = data[&#39;master_project_en&#39;].value_counts().head(20)  # Top 20 areas<br><br># Set plot style<br>plt.figure(figsize=(10, 8))<br>sns.set_theme(style=&quot;whitegrid&quot;)<br><br># Horizontal bar chart<br>ax = sns.barplot(<br>    x=area_counts.values, <br>    y=area_counts.index, <br>    palette=&quot;Blues_d&quot;,<br>    hue=area_counts.index<br>)<br><br># Add bar labels<br>for container in ax.containers: # annotate bars with counts<br>    ax.bar_label(container,fmt=&#39;%d&#39;, label_type=&#39;edge&#39;, padding=3)  <br><br>plt.title(&quot;Top 20 Areas by Number of Transactions&quot;, fontsize=14)<br>plt.xlabel(&quot;Number of Transactions&quot;)<br>plt.ylabel(&quot;Area Name&quot;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*BWzumIKeIQ8VmsyyZSePsg.png" /></figure><p><strong><em>Observation</em></strong><em>: The chart above shows that areas like </em><strong><em>Jumeirah Village Circle, Business Bay, Dubai Marina, </em></strong><em>among others,</em><strong><em> </em></strong><em>contribute a large number of transactions, indicating these areas are hotspots for property activity.</em></p><h4>4. Property Subtype Distribution</h4><p>The property_sub_type_en column provides a finer classification of the property (e.g., flat, villa, office, shop, etc.). Profiling the data shows that the dataset is largely focused on residential units. Below is the distribution of property sub-types by count:</p><pre>print(df[&#39;property_sub_type_en&#39;].value_counts())</pre><pre>property_sub_type_en<br>flat                  776436<br>villa                  95836<br>office                 51346<br>hotel_apartment        23385<br>hotel_rooms            13145<br>shop                   12264<br>workshop                 426<br>stacked_townhouses       349<br>store                    295<br>building                  77<br>clinic                    56<br>warehouse                 38<br>show_rooms                35<br>hotel                     12<br>gymnasium                  8<br>sized_partition            7<br>parking                    4<br>unit                       1</pre><p><strong><em>Observation</em></strong><em>: This listing reveals a classic long-tail distribution in property types.</em></p><p><strong><em>Flats (</em>~776k transactions<em>) </em></strong><em>make up the bulk of transactions by far, with </em><strong><em>villas</em></strong><em> </em><strong><em>(</em>~96k transactions<em>) </em></strong><em>being the second largest category. </em><strong><em>Commercial</em></strong><em> and specialty property types (offices, shops, hotel units, etc.) are relatively minor in frequency (</em>e.g. gymnasium, partition, parking have <strong>single-digit occurrences</strong><em>). The dominance of residential units means our analysis will be heavily weighted toward the housing market. This mix of residential and commercial properties could introduce heterogeneity in price drivers, so we may later filter or encode property type carefully.</em></p><h3>Exploratory Analysis of Numerical Features</h3><p>We now turn to the numerical features of the dataset to understand their distributions. Plotting histograms for the numeric columns provides a high-level overview:</p><pre>df.hist(bins=30, figsize=(15, 10))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sYSb_c19KGKFikDQbQSqZg.png" /></figure><ul><li><strong>Date Concentration:</strong> The top-left plot shows transaction count by year (the instance_date was converted to datetime and binned by year). The bars confirm that most transactions occurred in recent years — there’s modest activity around 2010–2012, but a sharp growth post-2020. The highest bar corresponds to <strong>2024</strong>, indicating a booming market in the latest years. This temporal skew means our dataset is heavily weighted toward the <strong>2020s</strong>, with relatively few records from the early 2000s.<br><strong><em>Underlying Drivers:</em></strong><em> This boom is driven by a confluence of factors. Post-COVID, Dubai’s openness and rapid economic rebound attracted remote workers and global investors. Visa reforms — notably the Golden Visa and property-linked investor residency schemes — made buying property more accessible to foreigners. Simultaneously, major infrastructure and Expo-related developments elevated demand across key districts. Fueled by strong capital inflows from other countries, record-high transaction volumes and prices followed — with total deals surpassing AED 500 billion in 2024 and $117 billion by mid-2025. These dynamics explain why our dataset is heavily concentrated in the most recent years.</em></li><li><strong>Skewed Price and Size Distributions:</strong> The distributions of sale price (actual_worth), property area (procedure_area), and price-per-square-meter field ( meter_rent_price) are all <strong>heavily right-skewed</strong>. Most properties are in the lower price and smaller size range, with a <strong>long tail extending to very high values</strong>.</li><li><strong>Parking Availability:</strong> The <strong>has_parking</strong> variable is binary (0 = no , 1 = yes). The histogram shows that the vast majority of transactions have has_parking = 1 , with roughly 67% of properties including parking.</li><li><strong>Rent-to-Own Fields:</strong> The rent_value and meter_rent_price fields (related to lease-to-own transactions) are populated in only a small subset of records (~34k entries, or roughly 3% of the data). Correspondingly, their histograms have much lower frequencies and they too are right-skewed when they are present.</li></ul><p>Overall, these distributions highlight the presence of <strong>outliers</strong>. Next, we quantify these outliers more formally.</p><h4>Distribution Ranges and Skewness</h4><p>We used a basic aggregation to summarize the range and variability of key numerical features such as actual_worth (sale price) and procedure_area (property size) to understand the data spread and flag obvious irregularities:</p><pre>df[[&#39;actual_worth&#39;, &#39;procedure_area&#39;]].agg([&#39;min&#39;, &#39;max&#39;, &#39;mean&#39;, &#39;std&#39;])<br></pre><p>This produced the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*FKvVzynBu50Chq6glKaC1Q.png" /></figure><p>We found transactions with property values as low as <strong>1 AED (!)</strong>, and areas smaller than <strong>0.01 sqm</strong> — both likely due to data entry errors or placeholder values<strong>. </strong>Meanwhile, some records show sales <strong>~AED 660 million</strong> or properties over <strong>55k sqm</strong>, which could represent bulk land deals or incorrect entries.</p><p>These extremes make formal outlier detection (e.g., using IQR) unreliable at this stage. Instead, they serve as a strong signal that <strong>data cleaning is essential</strong> before any robust analysis or modeling. In the next phase, we’ll refine the dataset by handling these anomalies and reassessing value ranges with confidence.</p><h3>Missing Data Analysis</h3><p>In addition to extreme values, we need to understand the completeness of our data. We assessed missing values for each feature both visually and quantitatively.</p><ul><li>A <strong>heatmap</strong> to see if missing values in different columns tend to occur together (darker blocks would indicate correlations in missingness).</li></ul><pre>msno.heatmap(df)  # Heatmap visualization to check the correlation between missing values<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pq7vvrgxillStq5WHxZueg.png" /></figure><p><em>Most features have weak or no correlation in their missingness. However, </em><em>nearest_metro_en and </em><em>nearest_mall_en show a moderate positive correlation (~0.5), suggesting shared gaps in data coverage. Meanwhile, </em><em>rent_value and </em><em>meter_rent_price have a perfect correlation in missingness (1.0), meaning they are always missing together</em></p><ul><li>A <strong>bar chart</strong> to show the count of missing entries per feature.</li></ul><pre>msno.bar(df)  # Bar chart visualization to check the number of missing values in each feature<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1MukDdHst9rnwLVSlkGFfA.png" /></figure><p>The <strong>bar chart </strong>plot gives a sense of how few rows have data for the rent-to-own fields — the very short bars show nearly all entries lack those fields</p><ul><li>A <strong>matrix</strong> visualization to get a detailed view of which entries are present or missing.</li></ul><pre>msno.matrix(df)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YeyzvE8jhToZZaEPYWUOJQ.png" /></figure><p>The visual analysis makes it clear that some columns have a lot of missing values. To get exact numbers, we computed missing value counts and percentages for each column:</p><pre># Helper function to summarize missing values<br>def missing_values_percentage(input_df):<br>    total_rows = input_df.shape[0]<br>    missing_values_count = input_df.isnull().sum()<br>    missing_values_percentage = (missing_values_count / total_rows) * 100<br>    missing_df = pd.DataFrame({<br>        &#39;column_name&#39;: missing_values_count.index,<br>        &#39;missing_count&#39;: missing_values_count.values,<br>        &#39;missing_ratio&#39;: missing_values_percentage.values<br>    })<br>    # Filter to only features that have at least one missing value<br>    missing_df = missing_df[missing_df[&#39;missing_ratio&#39;] &gt; 0]<br>    return missing_df<br><br># Compute and display missing value statistics<br>print(&quot;Statistics of missing values per feature:&quot;)<br>print(missing_values_percentage(df))</pre><pre>Statistics of missing values per feature:<br><br>            column_name  missing_count  missing_ratio<br>7      building_name_en          95701         10.558<br>8       project_name_en         167022         18.427<br>9     master_project_en          85181          9.398<br>10  nearest_landmark_en         160432         17.700<br>11     nearest_metro_en         237341         26.185<br>12      nearest_mall_en         240857         26.573<br>13             rooms_en            621          0.069<br>18           rent_value         881345         97.236<br>19     meter_rent_price         881345         97.236</pre><p>Several features stand out with notably high missingness:</p><ul><li><strong>rent_value</strong> &amp; <strong>meter_rent_price</strong> – ~97% of values missing. These fields only apply to lease-to-own transactions. This extreme sparsity means they contribute little information for most properties and would be very challenging to use in modeling without dropping or special handling.</li><li><strong>project_name_en</strong> – ~18% of entries missing. The combination of substantial missingness and over 2,912 distinct project values makes this feature difficult to leverage effectively without dropping it or significant preprocessing.</li><li><strong>building_name_en</strong> – ~11% of entries missing. Certain property types (e.g. standalone villas or land plots) simply do not have a building name, which explains these gaps. While most apartment entries include building info, a notable subset of listings lack this detail.</li><li><strong>Location proximity features</strong> (e.g. <strong>nearest_metro_en</strong>, <strong>nearest_mall_en</strong>) – Each has roughly 26% missing values. It appears some records (possibly older entries or transactions in remote areas) have no data for nearby amenities, suggesting the missingness here is systematic rather than random.</li><li><strong>Other features</strong> — A few columns have only negligible gaps (for example, <strong>rooms_en</strong> is missing in just 0.07% of records), which are unlikely to significantly impact our analysis.</li></ul><p>Recognizing these patterns is crucial: features with excessive missing data may need to be dropped or specially handled in the data cleaning phase.</p><h3>Feature Correlations</h3><p>To wrap up the initial exploration, we examined the linear relationships between numeric features using a correlation heatmap. This helps us identify potentially redundant features, strong dependencies, or surprising gaps in association.</p><pre># calculate the correlation matrix on the numeric columns<br>corr = df.corr(numeric_only=True)<br><br># plot the heatmap<br>sns.heatmap(corr)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*sUGYXrrQ2HEVsdoE1TkPrg.png" /></figure><p>The plot reveals a few intuitive patterns:</p><ul><li>actual_worth and meter_sale_price are moderately correlated, as expected since one is derived from the other.</li><li>rent_value and procedure_area also show strong correlation, likely reflecting how rent value scales with property size.</li><li>Features like has_parking show weak or even slightly negative correlation with monetary fields, suggesting limited predictive influence.</li></ul><p>This overview provides a valuable high-level signal on which features might be useful later — and which may be redundant or uninformative. We’ll take this into account during data cleaning and feature engineering in next parts.</p><h3>Initial Insights and Next Steps</h3><p>Our initial exploration reveals several key insights:</p><ul><li><strong>Scale and Recency Bias:</strong> The dataset is <strong>huge</strong> and <strong>recent-heavy</strong>. The majority of transactions occurred in the last few years, especially post-2020, reflecting Dubai’s real estate boom in the 2020s. Any modeling will need to account for time trends (e.g. market growth over years) or risk being skewed by the dominance of recent data.</li><li><strong>Dominance of Residential Sales:</strong> Sales of residential properties constitute the bulk of the data. Mortgages and gifts form a smaller fraction, and commercial property transactions are present but not as numerous. Our modeling efforts should focus on the dynamics of residential sales. We might treat other transaction types separately or filter them out when training models, to avoid mixing fundamentally different kinds of transactions.</li><li><strong>Data quality issues to address:</strong> We discovered significant missing data in some columns (e.g., project names, rent-to-own related fields) and a sizable share of outliers in price and area. Additionally, some categorical entries (like “office” in the rooms field) indicate that mixing commercial properties with residential might require us to filter or encode carefully.</li></ul><p>In the upcoming <strong>stories</strong>, we will tackle these issues. That will include dropping or imputing missing values, removing or capping outliers, encoding categorical variables (such as property subtypes and area names), and creating any new features (like extracting the year or month from instance_date). By cleaning the data and preparing it properly, we’ll set a solid foundation for building a reliable prediction model. Stay tuned!</p><p>*<em>(For those interested in the technical details or wanting to reproduce this analysis, the full code and notebook for this exploration are available on the project’s GitHub repository: </em><a href="https://github.com/ssuljo/dld_transactions_analytics/blob/main/data_preparation.ipynb"><em>https://github.com/ssuljo/dld_transactions_analytics/blob/main/data_preparation.ipynb</em></a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfca41c5d1a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate Llama3 with AWS SageMaker and Lambda]]></title>
            <link>https://medium.com/@skokhatska/integrate-llama3-with-aws-sagemaker-and-lambda-60f13f28b9c1?source=rss-8fcb7662e908------2</link>
            <guid isPermaLink="false">https://medium.com/p/60f13f28b9c1</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[hugging-face]]></category>
            <dc:creator><![CDATA[Svitlana Kokhatska]]></dc:creator>
            <pubDate>Sat, 20 Jul 2024 15:41:35 GMT</pubDate>
            <atom:updated>2025-08-18T07:52:58.557Z</atom:updated>
            <content:encoded><![CDATA[<h3>Take Your Own LLM to the Cloud: Real-Time Inference with Llama, AWS SageMaker, and Lambda</h3><h3>🚀 A Practical Guide to AI Deployment 🚀</h3><p>The integration of advanced language models like Llama 3 into your applications can significantly elevate their functionality, enabling sophisticated AI-driven insights and interactions. In this guide, you will be walked through a practical and systematic approach to deploying the <a href="https://medium.com/r?url=https%3A%2F%2Fhuggingface.co%2Fmeta-llama%2FMeta-Llama-3-8B-Instruct">Llama-3-8B-Instruct</a> model on AWS SageMaker and running inference from AWS Lambda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1nVH6xmB5CCygU5_qrlBhA.jpeg" /></figure><p>Whether you’re an AI developer, a data scientist, or a technology enthusiast, this article will provide you with clear, step-by-step instructions to get your model up and running efficiently. By leveraging the power of AWS services, you can achieve scalable and cost-effective deployment, making the process of integrating advanced AI into your workflows straightforward and highly beneficial.</p><p>From setting up the necessary IAM roles to configuring the SageMaker environment, deploying the model, and creating a Lambda function to invoke it, we will cover all essential aspects. This guide aims to equip you with the knowledge and tools to harness the capabilities of Llama 3, enabling you to enhance your projects with cutting-edge AI technology. Let’s get started! ✨</p><h3>Prerequisites:</h3><p>Before you start, ensure your AWS account is active and you have the necessary permissions to create and manage resources.</p><h4><strong>Create necessary IAM Roles for SageMaker and Lambda.</strong></h4><p>To deploy a model on SageMaker and invoke it using Lambda, you need IAM roles with the necessary permissions. These roles will allow SageMaker to access other AWS services, create endpoints, run predictions, and enable Lambda to invoke SageMaker endpoints.</p><ol><li><strong>Create an IAM Role for SageMaker</strong></li></ol><ul><li>Go to the AWS Management Console and navigate to the IAM service.</li><li>Create a new role named SageMaker-Execution-Role and select SageMaker as the trusted entity.</li><li>Attach the defaultAmazonSageMakerFullAccess policy to this role. For more restrictive access, refer to the <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/security-iam.html">AWS documentation</a>.</li></ul><p><strong>2. Create an IAM Role for Lambda</strong></p><ul><li>Create a custom policy named SageMakerInvokeEndpointPolicy using the following JSON policy. For detailed steps, refer to the <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create-console.html#access_policies_create-json-editor">AWS documentation</a>.</li></ul><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;sagemaker:DescribeEndpointConfig&quot;,<br>                &quot;sagemaker:DescribeEndpoint&quot;,<br>                &quot;sagemaker:InvokeEndpoint&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ]<br>}</pre><ul><li>Create a new role named Lambda-SageMaker-Invoke-Role and select Lambda as the trusted entity.</li><li>Attach two policies:<br>- Attach the defaultAWSLambdaBasicExecutionRole policy.<br>- Attach the custom SageMakerInvokeEndpointPolicy policy.</li></ul><p>By setting up these roles, you’ll ensure that both SageMaker and Lambda have the appropriate permissions to perform their respective tasks.</p><h4><strong>Set up your environment</strong></h4><ul><li><strong>Local Environment:</strong><br>Install and configure the AWS CLI on your local machine. Ensure your AWS CLI profile is set up in the AWS config file. For more information, refer to the <a href="https://docs.aws.amazon.com/cli/v1/userguide/cli-configure-files.html">AWS CLI configuration documentation</a>.</li><li><strong>SageMaker Notebook Environment:</strong><br>Launch a SageMaker Notebook instance with an attached execution role (SageMaker-Execution-Role created in previous steps). For details on how to create and configure a SageMaker Notebook, check the <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/howitworks-create-ws.html">SageMaker documentation</a>.</li></ul><p>By following these steps, you will have your environment prepared for deploying a Llama3 model on AWS SageMaker.</p><h3><strong>Deploy LLama3 to Sagemaker Real-Time Endpoint:</strong></h3><p>Execute the following steps in your development environment:</p><h4>Step 1: Install Required Libraries</h4><pre>!pip install transformers boto3 &quot;sagemaker&gt;=2.224.4&quot; awscli==1.33.24 --upgrade --quiet</pre><h4>Step 2: Retrieve SageMaker Execution Role ARN</h4><p>Next, retrieve the SageMaker execution role ARN. For local execution: specify your &lt;PROFILE_NAME&gt; and &lt;REGION_NAME&gt; and replace &lt;ROLE_NAME&gt; with your actual role name.</p><pre>import sagemaker<br>import boto3<br><br>try:<br>    role = sagemaker.get_execution_role()<br>    print(&quot;Running in SageMaker notebook instance&quot;)<br>except ValueError:<br>    # Specify profile name, region name and role name for local environment<br>    ROLE_NAME = &quot;&lt;ROLE_NAME&gt;&quot;<br>    PROFILE_NAME = &quot;default&quot;<br>    REGION_NAME = &quot;us-east-1&quot;<br><br>    # Initialize a boto3 session for local environment<br>    session = boto3.Session(profile_name=PROFILE_NAME, region_name=REGION_NAME)<br><br>    # Get sagemaker execution role ARN<br>    iam = boto3.client(&#39;iam&#39;)<br>    role = iam.get_role(RoleName=ROLE_NAME)[&#39;Role&#39;][&#39;Arn&#39;]<br>    print(&quot;Running in local environment&quot;)<br><br>print(f&quot;Execution Role ARN: {role}&quot;)</pre><h4>Step 3: Configure the Model</h4><p>Set up the configuration for your model.</p><ul><li>HF_MODEL_ID defines the model ID which is automatically loaded from <a href="https://huggingface.co/models">hf.co/models</a> when creating a SageMaker endpoint. All of the 🤗 Hub’s 10,000+ models are available through this environment variable.</li><li>&lt;HF_TASK&gt; defines the task for the 🤗 Transformers pipeline used. Refer to the <a href="https://huggingface.co/docs/transformers/main_classes/pipelines">complete list of tasks</a>.</li><li>Replace &lt;YOUR_HUGGINGFACE_HUB_TOKEN&gt; with your 🤗 hub token. More information on tokens <a href="https://huggingface.co/docs/hub/en/security-tokens">here</a>.</li><li>MESSAGES_API_ENABLED— will modify the /invocations route to accept Messages dictionaries consisting of role and content. More information on messages API <a href="https://huggingface.co/docs/text-generation-inference/en/messages_api">here</a>.</li><li><strong><em>Important: Accept the license terms on the </em></strong><a href="https://huggingface.co/meta-llama/Meta-Llama-3-70B-Instruct"><strong><em>Model Card</em></strong></a><strong><em>.</em></strong></li></ul><pre>HF_MODEL_ID = &quot;meta-llama/Meta-Llama-3-8B-Instruct&quot;<br>HF_TASK = &quot;text-generation&quot;<br>HF_TOKEN = &quot;&lt;YOUR_HUGGINGFACE_HUB_TOKEN&gt;&quot;<br>env = {<br>    &quot;HF_MODEL_ID&quot;: HF_MODEL_ID,<br>    &quot;HF_TASK&quot;: HF_TASK,<br>    &quot;HUGGING_FACE_HUB_TOKEN&quot;: HF_TOKEN,<br>    &quot;MESSAGES_API_ENABLED&quot;: &quot;True&quot;<br>}</pre><h4>Step 4: Create the Model Object</h4><p>Create a model object using the HuggingFaceModel class.</p><pre>import re<br>from sagemaker.huggingface import HuggingFaceModel, get_huggingface_llm_image_uri<br><br># Ensure endpoint name is compliant for AWS<br>regex = r&quot;[^\-a-zA-Z0-9]+&quot;<br>model_name = re.sub(regex, &quot;-&quot;, env[&quot;HF_MODEL_ID&quot;])<br><br># Get the HuggingFace LLM image URI<br>image_uri = get_huggingface_llm_image_uri(&quot;huggingface&quot;, version=&quot;2.0.2&quot;)<br><br>print(f&#39;llm image uri: {image_uri}&#39;)<br><br># create model itself<br>model = HuggingFaceModel(<br>    name=model_name,<br>    env=env,<br>    role=role,<br>    image_uri=image_uri,<br>)</pre><h4>Step 5: Deploy the Model to AWS SageMaker</h4><p>Deploy the model to an endpoint on SageMaker. This includes creating the model, endpoint configuration, and endpoint.</p><pre>from datetime import datetime<br><br>instance_type = &quot;ml.g5.2xlarge&quot;<br>init_instance_count = 1<br>health_check_timeout = 200<br><br># Generate a unique endpoint name using datetime<br>endpoint_name = f&#39;{model_name}-{datetime.now().strftime(&quot;%Y-%m-%d-%H-%M-%S&quot;)}&#39;<br>print(f&quot;endpoint_name: {endpoint_name}&quot;)<br><br># Deploy the model to an endpoint<br>predictor = model.deploy(<br>    endpoint_name=endpoint_name,<br>    instance_type=instance_type,<br>    initial_instance_count=init_instance_count,<br>    container_startup_health_check_timeout=health_check_timeout,<br>)</pre><p>Wait for the output similar to -----------! indicating that the model is deployed and ready for inference.</p><h4>Step 6: Test the Deployed Model</h4><pre>messages= [<br>    {<br>      &quot;role&quot;: &quot;system&quot;,<br>      &quot;content&quot;: &quot;You are a helpful assistant.&quot;<br>    },<br>    {<br>      &quot;role&quot;: &quot;user&quot;,<br>      &quot;content&quot;: &quot;Tell me about AWS SageMaker&quot;<br>    }<br>]</pre><pre># Send a test request to the deployed endpoint<br>input_data = {<br>    &quot;messages&quot;: messages,<br>    &quot;model&quot;:HF_MODEL_ID,<br>    &quot;max_tokens&quot;: 50, <br>    &quot;temperature&quot;: 0.7,<br>}<br><br># Print the prediction result<br>print(predictor.predict(input_data)[&#39;choices&#39;][0][&#39;message&#39;][&#39;content&#39;])</pre><p>It took me 1 second to receive the following generated text:</p><blockquote>AWS SageMaker is a fully managed service offered by Amazon Web Services (AWS) that provides a range of tools and capabilities to build, train, and deploy machine learning (ML) models. SageMaker simplifies the ML workflow by providing a comprehensive platform.</blockquote><h3>Create Lambda to Invoke Endpoint</h3><p>Now that the model is up and running, we can create a Lambda function to invoke the SageMaker endpoint.</p><h4>Step 1: Create a Function</h4><ul><li>Go to the AWS Management Console and navigate to the Lambda service.</li><li>Fill out the form with the <em>Function name</em>, <em>Python version</em>, and existing <em>Execution role name</em> (in our case it is Lambda-SageMaker-Invoke-Role)</li><li>Submit the form.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BjPjweYXHfckF0JgeWzNwg.png" /></figure><h4>Step 2: Configure Environment Variables</h4><p>On the <strong>Configuration tab</strong> specify Environment Variables:</p><ul><li>ENDPOINT_NAME: name of the newly created endpoint.</li><li>HF_MODEL_ID: 🤗 model ID for tokenizer (in our case, meta-llama/Meta-Llama-3-8B-Instruct).</li></ul><p>Correctly specified environment variables are crucial for configuring the tokenizer and connecting to the SageMaker runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9dpg5uwfKL8fkosd6bUM1g.png" /></figure><h4>Step 3: Increase Lambda timeout</h4><p>On the <strong>Configuration tab</strong> Increase timeout to 1 minute 0 seconds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GnQsj0DBNxfpU60cYj8ZQ.png" /></figure><h4>Step 3: Add lambda script</h4><p>On the Code tab in the editor, paste the following script and click <em>Deploy</em> button.</p><p>Additional parameters used for text generation task:</p><ul><li><strong>max_tokens: </strong>Defines the maximum number of tokens (words or word pieces) that can be generated by the model.</li><li><strong>temperature</strong>: Controls the randomness of the generated text. A lower temperature results in more deterministic and focused responses, while a higher temperature makes the output more random and creative.</li><li><strong>top_p</strong> : Specifies the cumulative probability threshold for token selection. The model considers only the top tokens with a cumulative probability up to top_p when generating each token. 0.2 means the model will consider only the top 20% of the probability mass when selecting the next token.</li></ul><pre>import boto3<br>import os<br>import json<br><br># Initialize the boto3 client for SageMaker runtime<br>client = boto3.client(service_name=&quot;sagemaker-runtime&quot;)<br><br># Load environment variables<br>MODEL_ID = os.environ.get(&quot;HF_MODEL_ID&quot;)<br>ENDPOINT_NAME = os.environ.get(&quot;ENDPOINT_NAME&quot;)<br><br># Define parameters for LLM<br>parameters = {<br>    &quot;model&quot;: MODEL_ID,<br>    &quot;max_tokens&quot;: 3000,<br>    &quot;temperature&quot;: 0.5,<br>    &quot;top_p&quot;: 0.2,<br>}<br><br># Invoke the SageMaker endpoint<br>def invoke_endpoint_for_inference(client, prompt, parameters):<br>    payload = {<br>        &quot;messages&quot;: prompt,<br>         **parameters,<br>    }<br>    try:<br>        response = client.invoke_endpoint(<br>            EndpointName=ENDPOINT_NAME,<br>            ContentType=&quot;application/json&quot;,<br>            Accept=&quot;application/json&quot;,<br>            Body=json.dumps(payload),<br>        )<br>        response_body = response[&quot;Body&quot;].read().decode(&quot;utf-8&quot;)<br>        response_json = json.loads(response_body)<br>        generated_text = response_json[&#39;choices&#39;][0][&#39;message&#39;][&#39;content&#39;]<br>        return generated_text<br>    except Exception as e:<br>        print(f&quot;Error invoking endpoint: {e}&quot;)<br>        raise<br><br># Validate the incoming event to ensure it contains the required &#39;messages&#39; key<br>def validate_event(event):<br>    if &quot;messages&quot; not in event:<br>        raise ValueError(&quot;Missing &#39;messages&#39; in the event payload.&quot;)<br>    return event[&quot;messages&quot;]<br><br># Main Lambda function handler <br>def lambda_handler(event, context):<br>    try:<br>        print(&quot;Received event: &quot; + json.dumps(event, indent=2))<br><br>        messages = validate_event(event)<br><br>        response = invoke_endpoint_for_inference(<br>            client, messages, parameters<br>        )<br><br>        print(response)<br><br>        return {<br>            &quot;statusCode&quot;: 200,<br>            &quot;isBase64Encoded&quot;: False,<br>            &quot;body&quot;: json.dumps(response),<br>        }<br><br>    except Exception as err:<br>        return {<br>            &quot;statusCode&quot;: 400,<br>            &quot;isBase64Encoded&quot;: False,<br>            &quot;body&quot;: &quot;Call Failed {0}&quot;.format(err),<br>        }</pre><h4>Step 4: Send Test Event</h4><p>Create a test event with the following JSON input.</p><pre>{<br>  &quot;messages&quot;: [<br>    {<br>      &quot;role&quot;: &quot;system&quot;,<br>      &quot;content&quot;: &quot;You are a helpful financial advisor.&quot;<br>    },<br>    {<br>      &quot;role&quot;: &quot;user&quot;,<br>      &quot;content&quot;: &quot;What are the most profitable stocks of all time?&quot;<br>    }<br>  ]<br>}</pre><p>Send the test event and wait for the response. Instructions on testing lambda functions can be found <a href="https://docs.aws.amazon.com/lambda/latest/dg/testing-functions.html#:~:text=Open%20the%20Functions%20page%20of,that%20you%20want%20to%20use.">here</a>.</p><p>For me, it took 22 seconds to receive the following response:</p><blockquote>What a great question! As a financial advisor, I’d be happy to share with you some of the most profitable stocks of all time. Keep in mind that past performance is not a guarantee of future results, and it’s essential to do your own research and consider your individual financial goals and risk tolerance before investing in any stock.</blockquote><blockquote>That being said, here are some of the most profitable stocks of all time:</blockquote><blockquote>1. Amazon (AMZN) — Up over 100,000% since its IPO in 1997. Yes, you read that right — 100,000%!</blockquote><blockquote>2. Microsoft (MSFT) — Up over 50,000% since its IPO in 1986. Microsoft’s dominance in the software industry has made it a behemoth in the tech world.</blockquote><blockquote>3. Alphabet (GOOGL) — Up over 20,000% since its IPO in 2004. As the parent company of Google, Alphabet has revolutionized the way we search, advertise, and access information online.</blockquote><blockquote>4. Facebook (FB) — Up over 10,000% since its IPO in 2012. Facebook’s social media platform has become an integral part of modern life, making it a highly profitable investment.</blockquote><blockquote>5. Johnson &amp; Johnson (JNJ) — Up over 10,000% since its IPO in 1944. This healthcare giant has a diverse portfolio of pharmaceuticals, medical devices, and consumer products.</blockquote><blockquote>6. Procter &amp; Gamble (PG) — Up over 9,000% since its IPO in 1890. This consumer goods company has been a staple in many households for over a century, with a portfolio of iconic brands like Tide, Pampers, and Gillette.</blockquote><blockquote>7. Coca-Cola (KO) — Up over 8,000% since its IPO in 1919. The world’s largest beverage company has been a consistent performer over the years, with a portfolio of beloved brands like Coke, Fanta, and Sprite.</blockquote><blockquote>8. Visa (V) — Up over 7,000% since its IPO in 2008. As a leading payment technology company, Visa has benefited from the shift towards digital payments and e-commerce.</blockquote><blockquote>9. Mastercard (MA) — Up over 6,000% since its IPO in 2006. Similar to Visa, Mastercard has also seen significant growth as a leading payment technology company.</blockquote><blockquote>10. Intel (INTC) — Up over 5,000% since its IPO in 1971. As a pioneer in the semiconductor industry, Intel has played a crucial role in the development of modern computing and has remained a dominant player in the tech sector.</blockquote><blockquote>Remember, these returns are exceptional and not typical of most stocks. It’s essential to diversify your portfolio, set realistic expectations, and consult with a financial advisor before making any investment decisions.</blockquote><h3>Clean up</h3><p>Do not forget to delete the SageMaker real-time endpoint as it is charged by the hour. You can run the code in your development environment or do it through the AWS Management Console.</p><pre>sagemaker_client = boto3.client(&#39;sagemaker&#39;)<br>sagemaker_client.delete_endpoint(EndpointName=endpoint_name)</pre><h3>Conclusion</h3><p>By leveraging the power of AWS services, you can achieve scalable, efficient, and cost-effective deployment of advanced AI models. This guide has provided a step-by-step approach to setting up the necessary IAM roles, configuring the SageMaker environment, deploying the LLM model, and creating a Lambda function to invoke the endpoint.</p><p>With the model deployed and tested successfully, you now have a robust solution for real-time inference that can be adapted to various applications, from generating content to making predictions based on user inputs. Remember to manage your AWS resources carefully, particularly the SageMaker endpoints, to optimize costs.</p><blockquote>You can find all the code referenced in this article on GitHub <a href="https://github.com/ssuljo/llama3-sagemaker-lambda.git">here</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60f13f28b9c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>