<?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 Tom Haber on Medium]]></title>
        <description><![CDATA[Stories by Tom Haber on Medium]]></description>
        <link>https://medium.com/@tomhaber36?source=rss-5a2cf8baaff2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Tw2873Una3_N3x-m.jpg</url>
            <title>Stories by Tom Haber on Medium</title>
            <link>https://medium.com/@tomhaber36?source=rss-5a2cf8baaff2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 12:05:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tomhaber36/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[Maximizing Model Performance with LightGBM, MLflow, and Optuna: A Titanic Dataset Case Study]]></title>
            <link>https://medium.com/@tomhaber36/maximizing-model-performance-with-lightgbm-mlflow-and-optuna-a-titanic-dataset-case-study-7aa070d06a13?source=rss-5a2cf8baaff2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7aa070d06a13</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[optuna]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[lightgbm]]></category>
            <dc:creator><![CDATA[Tom Haber]]></dc:creator>
            <pubDate>Sun, 31 Dec 2023 10:26:28 GMT</pubDate>
            <atom:updated>2023-12-31T10:26:28.537Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*cyX3M208UKOQyLCZIj5_Bg.jpeg" /></figure><h3>Introduction</h3><p>In the rapidly evolving field of data science, there is a growing interest in leveraging advanced techniques like Large Language Models (LLMs) for AI applications. While LLMs have garnered attention, it’s essential to remember that tabular data remains a cornerstone, requiring advanced techniques to maximize model performance. This article explores the integration of LightGBM, MLflow, and Optuna in a unified workflow, focusing on optimizing model parameters without delving into feature engineering. The analysis centers on the renowned Titanic dataset, a tabular dataset with the binary survival outcome.</p><h3>Titanic Dataset Overview</h3><p>The Titanic dataset is a classic dataset widely used for machine-learning exercises. For the purpose of this study, we will focus on specific features: Pclass, Sex, Age, SibSp, Parch, Fare, Embarked, and Survived. The goal is to build a model that predicts whether a passenger survived or not based on these features. It&#39;s important to note that we will not perform any feature engineering in this analysis, but rather concentrate on optimizing the LightGBM model through parameter tuning.</p><p>The dataset can be accessed and downloaded from <a href="https://www.kaggle.com/c/titanic/data?select=train.csv">Kaggle</a></p><p><strong>Example Rows of Titanic Dataset:</strong></p><pre>| Pclass | Sex    | Age  | SibSp | Parch | Fare     | Embarked | Survived |<br>|--------|--------|------|-------|-------|----------|----------|----------|<br>| 3      | male   | 22.0 | 1     | 0     | 7.25     | S        | 0        |<br>| 1      | female | 38.0 | 1     | 0     | 71.2833  | C        | 1        |<br>| 3      | female | 26.0 | 0     | 0     | 7.925    | S        | 1        |<br>| 1      | female | 35.0 | 1     | 0     | 53.1     | S        | 1        |<br>| 3      | male   | 35.0 | 0     | 0     | 8.05     | S        | 0        |</pre><h3>Why LightGBM?</h3><p>Before delving into model development, let’s understand why LightGBM is a powerful choice for this task. LightGBM, a gradient-boosting framework, stands out for its speed and efficiency. Its leaf-wise tree growth strategy and histogram-based approach make it well-suited for large datasets. The ability to handle categorical features and robust performance in diverse scenarios make LightGBM an essential tool in a data scientist’s arsenal.</p><p>Key Parameters and Capabilities of LightGBM:</p><ul><li>boosting_type: Specify the boosting method (e.g., gbdt, dart).</li><li>num_leaves: Control the maximum number of leaves in one tree.</li><li>learning_rate: Adjust the step size in each iteration.</li><li>max_depth: Set the maximum depth of the tree.</li><li>objective: Define the optimization objective (e.g., binary classification).</li></ul><h3>Initial Model Evaluation</h3><p>Now, let’s proceed with the initial model evaluation. Before diving into hyperparameter optimization, we evaluate the performance of a basic LightGBM model on the Titanic dataset using the F1 score, a metric that balances precision and recall.</p><pre># Import necessary libraries<br>import pandas as pd<br>from sklearn.metrics import f1_score<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import f1_score, confusion_matrix<br>import lightgbm as lgb<br>import optuna<br>import mlflow<br>import mlflow.lightgbm<br><br><br># Load Titanic dataset<br>titanic_data = pd.read_csv(&#39;titanic.csv&#39;)  # Assuming the dataset is stored in &#39;titanic.csv&#39;<br><br># Select specific features<br>selected_features = [&#39;Pclass&#39;, &#39;Sex&#39;, &#39;Age&#39;, &#39;SibSp&#39;, &#39;Parch&#39;, &#39;Fare&#39;, &#39;Embarked&#39;, &#39;Survived&#39;]<br>titanic_data = titanic_data[selected_features]<br><br># Convert categorical features to numerical using one-hot encoding<br>titanic_data = pd.get_dummies(titanic_data, columns=[&#39;Sex&#39;, &#39;Embarked&#39;], drop_first=True)<br><br><br># Extract features and target variable<br>X = titanic_data.drop(&#39;Survived&#39;, axis=1)<br>y = titanic_data[&#39;Survived&#39;]<br><br># Split dataset<br>X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># Train an initial LightGBM model<br>initial_model = lgb.train({}, lgb.Dataset(X_train, label=y_train), 100)<br><br># Make predictions and calculate F1 score<br>y_pred_initial = initial_model.predict(X_valid)<br>f1_initial = f1_score(y_valid, (y_pred_initial &gt; 0.5).astype(int))<br><br># Display F1 Score and Confusion Matrix<br>print(f&quot;Initial F1 Score: {f1_initial}&quot;)<br>print(&quot;Confusion Matrix:&quot;)<br>print(confusion_matrix(y_valid, (y_pred_initial &gt; 0.5).astype(int)))</pre><p>After training the initial LightGBM model on the Titanic dataset, the model achieved an F1 Score of approximately 0.79. Breaking down the results further with a confusion matrix:</p><p>[[92 13]<br> [17 57]]</p><p>In the confusion matrix:</p><ul><li>True Positive (TP): 92</li><li>False Positive (FP): 13</li><li>False Negative (FN): 17</li><li>True Negative (TN): 57</li></ul><h3>The Significance of Tabular Data and Parameter Tuning</h3><p>In the contemporary AI landscape, Large Language Models (LLMs) often steal the spotlight, but the importance of tabular data and advanced techniques in maximizing model performance should not be overlooked. In this case study, we refrain from feature engineering and concentrate on optimizing the LightGBM model through parameter tuning.</p><h3>MLflow for Experiment Tracking</h3><p>MLflow simplifies the machine learning lifecycle by offering tools to manage experiments, track parameters, and store models. Its logging capabilities facilitate collaboration among team members, enabling reproducibility and efficient model comparison.</p><p>Key Capabilities of MLflow:</p><ul><li><strong>Tracking Experiments</strong>: Log parameters, metrics, and artifacts to record and compare experiments.</li><li><strong>Model Packaging</strong>: Easily package and share models in a standardized format.</li><li><strong>Model Deployment</strong>: Simplify the deployment process with MLflow’s deployment options.</li></ul><h3>Optuna for Hyperparameter Optimization</h3><p>Optuna automates the hyperparameter optimization process, helping data scientists find the best combination of parameters efficiently. Its framework supports various optimization algorithms, making it adaptable to different optimization scenarios.</p><p>Key Capabilities of Optuna:</p><ul><li><strong>Distributed Optimization</strong>: Parallelize hyperparameter search across multiple nodes.</li><li><strong>Pruning</strong>: Accelerate optimization by early-stopping unpromising trials.</li><li><strong>Scalability</strong>: Scale up optimization efforts for complex models and large datasets.</li></ul><h3>Integrating LightGBM, MLflow, and Optuna</h3><p>Below is a simplified example of integrating LightGBM with MLflow and Optuna using the Titanic dataset:</p><pre># Define LightGBM objective function for Optuna<br>def objective(trial):<br>    params = {<br>        &#39;objective&#39;: &#39;binary&#39;,<br>        &#39;metric&#39;: &#39;binary_error&#39;,<br>        &#39;boosting_type&#39;: &#39;gbdt&#39;,<br>        &#39;num_leaves&#39;: trial.suggest_int(&#39;num_leaves&#39;, 2, 256),<br>        &#39;max_depth&#39;: trial.suggest_int(&#39;max_depth&#39;, 2, 32),<br>        &#39;learning_rate&#39;: trial.suggest_loguniform(&#39;learning_rate&#39;, 0.005, 0.5),<br>        &#39;feature_fraction&#39;: trial.suggest_uniform(&#39;feature_fraction&#39;, 0.1, 1.0),<br>    }<br><br>    # Set Train and Valid datasets<br>    lgb_train = lgb.Dataset(X_train, y_train)<br>    lgb_valid = lgb.Dataset(X_valid, y_valid, reference=lgb_train)<br><br>    # Train the model<br>    model = lgb.train(params, lgb_train, num_boost_round=100, valid_sets=[lgb_train, lgb_valid], <br>                      callbacks=[lgb.record_evaluation({&quot;valid&quot;: lgb_valid})])<br><br>    # Make predictions and calculate F1 score<br>    y_pred = model.predict(X_valid, num_iteration=model.best_iteration)<br>    f1 = f1_score(y_valid, (y_pred &gt; 0.5).astype(int))<br><br>    # Log parameters and metrics with MLflow<br>    with mlflow.start_run():<br>        mlflow.log_params(params)<br>        mlflow.log_metric(&#39;f1&#39;, f1)<br>        # Save the model as an artifact<br>        mlflow.lightgbm.log_model(model, &quot;model&quot;)<br><br>    return f1<br># Optimize hyperparameters with Optuna<br>study = optuna.create_study(direction=&#39;maximize&#39;)<br>study.optimize(objective, n_trials=100)</pre><ol><li><strong>Objective Function Definition:</strong></li></ol><ul><li>The objective function defines the hyperparameters that Optuna will optimize.</li><li>It sets up a dictionary (params) containing hyperparameters such as the objective, metric, boosting type, number of leaves, max depth, learning rate, and feature fraction.</li></ul><p><strong>2. Dataset Preparation:</strong></p><ul><li>LightGBM datasets (lgb_train and lgb_valid) are created using the training (X_train, y_train) and validation (X_valid, y_valid) data.</li></ul><p><strong>3. Model Training:</strong></p><ul><li>The LightGBM model is trained with the current set of hyperparameters using the training dataset (lgb_train).</li><li>The model is validated on the validation dataset (lgb_valid), and training progress is recorded with the record_evaluation callback.</li></ul><p><strong>4. Prediction and Metric Calculation:</strong></p><ul><li>Predictions are made on the validation set, and the F1 score is calculated using the f1_score function.</li></ul><p><strong>5. Logging with MLflow:</strong></p><ul><li>A new MLflow run is started, and the hyperparameters (params) and F1 score are logged.</li><li>The trained LightGBM model is saved as an artifact with the name “model.”</li></ul><p><strong>6. Optimization with Optuna:</strong></p><ul><li>The Optuna study is created to optimize the objective function (maximize F1 score) over a specified number of trials (n_trials).</li></ul><p>This process iteratively refines hyperparameters to find the combination that maximizes the F1 score. The final model and optimal hyperparameters are then logged using MLflow.</p><p><strong>Tracking with MLflow</strong></p><p>To view model runs and metrics logged in MLflow, follow these steps:</p><ol><li>Install MLflow: pip install mlflow</li><li>Start the MLflow UI: Run mlflow ui in your terminal.</li><li>Open your browser and go to http://localhost:5000 to access the MLflow UI.</li><li>Explore the recorded runs, metrics, and parameters.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3rb3ErBIePfCb7DYtYho9g.png" /></figure><p>Logging models with MLflow provides an organized record of each iteration’s configuration, facilitating easy comparison and decision-making. The MLflow UI acts as a user-friendly control center, offering insights into model performance and aiding in the seamless exploration and utilization of trained models.</p><h3>Training the Final Model</h3><p>Training once more with the optimal parameters identified by the Optuna process, we establish our ‘final_model.’ Now equipped with the best parameters, this final model is primed for evaluation on the test data.</p><pre># Train the final model with the best hyperparameters<br>best_params = study.best_params<br>final_model = lgb.train(best_params, lgb.Dataset(X_train, label=y_train), num_boost_round=100)<br><br># Make predictions and calculate F1 score<br>y_pred_final = final_model.predict(X_valid)<br>f1_final = f1_score(y_valid, (y_pred_final &gt; 0.5).astype(int))<br><br># Display F1 Score and Confusion Matrix<br>print(f&quot;Final Model F1 Score: {f1_final}&quot;)<br>print(&quot;Confusion Matrix:&quot;)<br>print(confusion_matrix(y_valid, (y_pred_final &gt; 0.5).astype(int)))</pre><p>After optimizing the LightGBM model using the Optuna hyperparameter tuning technique, the final F1 Score achieved is approximately <strong>0.81</strong></p><p>Confusion Matrix:</p><p>[[92 13]<br> [15 59]]</p><p>In the confusion matrix:</p><ul><li>True Positive (TP): 92</li><li>False Positive (FP): 13</li><li>False Negative (FN): 15</li><li>True Negative (TN): 59</li></ul><p>The F1 Score of 0.81 signifies a noteworthy enhancement compared to the initial model’s performance. Notably, through the streamlined Optuna, MLflow, and LightGBM process, we achieved a significant accuracy boost without delving into any intricate feature engineering efforts. This underscores the effectiveness of our approach in maximizing model accuracy through strategic parameter tuning.</p><h3>Conclusion</h3><p>In conclusion, this case study illustrates the significance of advanced techniques in maximizing model performance with tabular data. By leveraging LightGBM, MLflow, and Optuna, the article demonstrates a streamlined workflow for optimizing model parameters without engaging in feature engineering. The focus on parameter tuning in this scenario provides insights into the potential improvements achievable through more intricate feature engineering. As the AI industry embraces new buzzwords like Large Language Models (LLMs), it remains imperative to tackle tabular data with advanced techniques for robust model development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7aa070d06a13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[R dplyr vs Python pandas: A Showdown of Data Manipulation Powerhouses]]></title>
            <link>https://blog.devgenius.io/r-dplyr-vs-python-pandas-a-showdown-of-data-manipulation-powerhouses-2c92d63f6fa0?source=rss-5a2cf8baaff2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c92d63f6fa0</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[dplyr]]></category>
            <category><![CDATA[data-manipulation]]></category>
            <dc:creator><![CDATA[Tom Haber]]></dc:creator>
            <pubDate>Sun, 11 Dec 2022 13:21:55 GMT</pubDate>
            <atom:updated>2022-12-21T12:43:10.816Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tCXB9KWObzlSwcTyVx0nig.png" /></figure><p>Data manipulation and analysis are crucial tasks in many fields, it is important to be able to quickly and easily manipulate and analyze large datasets. Two popular tools for data manipulation and analysis are Python pandas and dplyr R.</p><p>While these two tools have some similarities, they are designed and used differently. In this article, we will compare pandas and dplyr, highlighting their key differences and showing how they can be used to solve common data manipulation problems using common and advanced capabilities such as filter, arrange, group by, select, join, and window functions.</p><p>We will use made-up housing data to show the capabilities of each tool.</p><p><strong>Filter</strong></p><p>One common data manipulation task is to filter data based on certain criteria. Both pandas and dplyr provide tools for filtering data.</p><p>Here is an example of how to use pandas to filter housing data:</p><pre>import pandas as pd<br><br># load the data from a CSV file<br>df = pd.read_csv(&#39;housing_data.csv&#39;)<br><br># filter the data frame to only include houses with a price greater than $500,000, at least 3 bedrooms, and a square footage greater than 1,500<br>df = df[(df[&#39;price&#39;] &gt; 500000) &amp; (df[&#39;bedrooms&#39;] &gt;= 3) &amp; (df[&#39;sq_ft&#39;] &gt; 1500)]<br><br># view the first few rows of the filtered data<br>df.head()<br>#   house_id     date     price  bedrooms  sq_ft  bathrooms  zipcode<br>#        3   1/3/2020  1020000         3   1600          2    90210<br>#        4   1/4/2020  1030000         3   1700          2    90210<br>#        5   1/5/2020  1040000         3   1800          2    90210<br>#        6   1/6/2020  1050000         3   1900          2    90210</pre><p>Here is an example of how to use dplyr to filter housing data:</p><pre># install and load the dplyr package<br>install.packages(&quot;dplyr&quot;)<br>library(dplyr)<br><br># load the data from a CSV file<br>df &lt;- read.csv(&#39;housing_data.csv&#39;)<br><br># filter the data frame to only include houses with a price greater than $500,000, at least 3 bedrooms, and a square footage greater than 1,500<br>df &lt;- df %&gt;%<br>  filter(price &gt; 500000, bedrooms &gt;= 3, sq_ft &gt; 1500)<br><br># view the first few rows of the filtered data<br>head(df)<br>#   house_id     date     price  bedrooms  sq_ft  bathrooms  zipcode<br>#        3   1/3/2020  1020000         3   1600          2    90210<br>#        4   1/4/2020  1030000         3   1700          2    90210<br>#        5   1/5/2020  1040000         3   1800          2    90210<br>#        6   1/6/2020  1050000         3   1900          2    90210</pre><p><strong>Arrange</strong></p><p>Another common data manipulation task is to sort data based on certain criteria. Both pandas and dplyr provide tools for sorting data.</p><p>Here is an example of how to use pandas to sort housing data:</p><pre># sort the data frame by the &#39;price&#39; column in descending order, and then by the &#39;bedrooms&#39; column in ascending order<br>df = df.sort_values([&#39;price&#39;, &#39;bedrooms&#39;], ascending=[False, True])<br><br># view the first few rows of the sorted data frame<br>df.head()<br>#   house_id     date     price  bedrooms  sq_ft  bathrooms  zipcode<br>#        6   1/6/2020  1050000         3   1900          2    90210<br>#        5   1/5/2020  1040000         3   1800          2    90210<br>#        4   1/4/2020  1030000         3   1700          2    90210<br>#        3   1/3/2020  1020000         3   1600          2    90210</pre><p>Here is an example of how to use dplyr to sort housing data:</p><pre># sort the data frame by the &#39;price&#39; column in descending order, and then by the &#39;bedrooms&#39; column in ascending order<br>df &lt;- df %&gt;%<br>  arrange(desc(price), bedrooms)<br><br># view the first few rows of the sorted data frame<br>head(df)<br>#   house_id     date     price  bedrooms  sq_ft  bathrooms  zipcode<br>#        6   1/6/2020  1050000         3   1900          2    90210<br>#        5   1/5/2020  1040000         3   1800          2    90210<br>#        4   1/4/2020  1030000         3   1700          2    90210<br>#        3   1/3/2020  1020000         3   1600          2    90210<br></pre><p><strong>Group by</strong></p><p>Another common data manipulation task is to group data based on certain criteria and then perform operations on the groups. Both pandas and dplyr provide tools for grouping data.</p><p>Here is an example of how to use pandas to group housing data:</p><pre># group the data frame by the &#39;zipcode&#39; column and calculate the mean price for each group<br>df = df.groupby(&#39;zipcode&#39;)[&#39;price&#39;].mean()<br><br># view the resulting data frame<br>df<br># zipcode<br># 90210    1040000<br># 90211    1050000<br># 90212    1020000</pre><p>Here is an example of how to use dplyr to group housing data:</p><pre># group the data frame by the &#39;zipcode&#39; column and calculate the mean price for each group<br>df &lt;- df %&gt;%<br>  group_by(zipcode) %&gt;%<br>  summarise(mean_price = mean(price))<br><br># view the resulting data frame<br>df<br># zipcode  mean_price<br># 90210    1040000<br># 90211    1050000<br># 90212    1020000</pre><p><strong>Select</strong></p><p>Another common data manipulation task is to select specific columns or rows from a data frame. Both pandas and dplyr provide tools for selecting data.</p><p>Here is an example of how to use pandas to select columns from a housing data frame:</p><pre># select the &#39;date&#39;, &#39;price&#39;, and &#39;zipcode&#39; columns from the data frame<br>df = df[[&#39;date&#39;, &#39;price&#39;, &#39;zipcode&#39;]]<br><br># view the first few rows of the resulting data frame<br>df.head()<br>#      date   price    zipcode<br>#   1/3/2020  1020000    90210<br>#   1/4/2020  1030000    90210<br>#   1/5/2020  1040000    90210<br>#   1/6/2020  1050000    90210</pre><p>Here is an example of how to use dplyr to select columns from a housing data frame:</p><pre># select the &#39;date&#39;, &#39;price&#39;, and &#39;zipcode&#39; columns from the data frame<br>df &lt;- df %&gt;%<br>  select(date, price, zipcode)<br><br># view the first few rows of the resulting data frame<br>head(df)<br>#    date    price    zipcode<br>#  1/3/2020  1020000    90210<br>#  1/4/2020  1030000    90210<br>#  1/5/2020  1040000    90210<br>#  1/6/2020  1050000    90210</pre><p><strong>Join</strong></p><p>Another common data manipulation task is to join data from multiple sources. Both pandas and dplyr provide tools for joining data.</p><p>Here is an example of how to use pandas to join two housing data frames on the house_id column:</p><pre># load the second data frame from a CSV file<br>df2 = pd.read_csv(&#39;housing_data_2.csv&#39;)<br><br># join the two data frames on the &#39;house_id&#39; column, using an inner join to only include rows with matching values in both data frames<br>df = df.join(df2, on=&#39;house_id&#39;, how=&#39;inner&#39;)<br><br># view the first few rows of the resulting data frame<br>df.head()<br>#   house_id     date     price  zipcode       city     state  year_built<br>#        3   1/3/2020  1020000    90210  Beverly Hills    CA        1950<br>#        4   1/4/2020  1030000    90210  Beverly Hills    CA        1960<br>#        5   1/5/2020  1040000    90210  Beverly Hills    CA        1970<br>#        6   1/6/2020  1050000    90210  Beverly Hills    CA        1980</pre><p>Here is an example of how to use dplyr to join two housing data frames on the house_id column:</p><pre># load the second data frame from a CSV file<br>df2 &lt;- read.csv(&#39;housing_data_2.csv&#39;)<br><br># join the two data frames on the &#39;house_id&#39; column, using an inner join to only include rows with matching values in both data frames<br>df &lt;- df %&gt;%<br>  inner_join(df2, by=&#39;house_id&#39;)<br><br># view the first few rows of the resulting data frame<br>head(df)<br>#   house_id     date     price  zipcode       city     state  year_built<br>#        3   1/3/2020  1020000    90210  Beverly Hills    CA        1950<br>#        4   1/4/2020  1030000    90210  Beverly Hills    CA        1960<br>#        5   1/5/2020  1040000    90210  Beverly Hills    CA        1970<br>#        6   1/6/2020  1050000    90210  Beverly Hills    CA        1980</pre><p>There are more joining operations we can process using dplyr and pandas such as left_join,right_join, and full_join.</p><p><strong>Window functions</strong></p><p>Another advanced data manipulation capability is the use of window functions, which allow you to perform calculations across a set of rows related to the current row. Both pandas and dplyr provide tools for using window functions.</p><p>Here is an example of how to use pandas to calculate the difference between the current rows price and the previous rows price using a window function:</p><pre># define the window function that calculates the difference between the current rows &#39;price&#39; and the previous rows &#39;price&#39;<br>def price_diff(df):<br>  return df[&#39;price&#39;] - df[&#39;price&#39;].shift(1)<br><br># apply the window function to the data frame, grouping by the &#39;zipcode&#39; column<br>df = df.groupby(&#39;zipcode&#39;).apply(price_diff)<br><br># view the first few rows of the resulting data frame<br>df.head()<br>#   house_id     date  price  zipcode       city        state  year_built price_diff<br>#        3  1/3/2020  1020000    90210  Beverly Hills    CA        1950       NaN<br>#        4  1/4/2020  1030000    90210  Beverly Hills    CA        1960     10000<br>#        5  1/5/2020  1040000    90210  Beverly Hills    CA        1970     10000<br>#        6  1/6/2020  1050000    90210  Beverly Hills    CA        1980     10000</pre><p>Here is an example of how to use pandas to calculate the difference between the current rows price and the previous row&#39;s price using a window function:</p><pre># define the window function that calculates the difference between the current rows &#39;price&#39; and the previous rows &#39;price&#39;<br>price_diff &lt;- function(df) {<br>  df %&gt;%<br>    mutate(price_diff = price - lag(price))<br>}<br><br># apply the window function to the data frame, grouping by the &#39;zipcode&#39; column<br>df &lt;- df %&gt;%<br>  group_by(zipcode) %&gt;%<br>  price_diff()<br><br># view the first few rows of the resulting data frame<br>head(df)<br>#   house_id     date     price  zipcode       city     state  year_built price_diff<br>#        3   1/3/2020  1020000    90210  Beverly Hills    CA        1950        NA<br>#        4   1/4/2020  1030000    90210  Beverly Hills    CA        1960     10000<br>#        5   1/5/2020  1040000    90210  Beverly Hills    CA        1970     10000<br>#        6   1/6/2020  1050000    90210  Beverly Hills    CA        1980     10000</pre><p>Other than using lag in window functions, there are more common functions to use like row_number, rank, and dense_rank. The usage of lag is simply to show how we can approach window function with pandas and dplyr.</p><p><strong>Conclusion</strong></p><p>In conclusion, pandas and dplyr are both powerful tools for data manipulation and analysis. While they have some similarities, they are designed and used in different ways, and each has its strengths and weaknesses. By understanding the key differences between pandas and dplyr, you can choose the right tool for your data manipulation and analysis tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c92d63f6fa0" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/r-dplyr-vs-python-pandas-a-showdown-of-data-manipulation-powerhouses-2c92d63f6fa0">R dplyr vs Python pandas: A Showdown of Data Manipulation Powerhouses</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XGBoosting Your Predictions: A Practical Guide using the Titanic Dataset]]></title>
            <link>https://medium.com/@tomhaber36/xgboosting-your-predictions-a-practical-guide-using-the-titanic-dataset-ae9cf1a63bbc?source=rss-5a2cf8baaff2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae9cf1a63bbc</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[f1-score]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Tom Haber]]></dc:creator>
            <pubDate>Wed, 07 Dec 2022 19:39:21 GMT</pubDate>
            <atom:updated>2022-12-07T19:39:21.888Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*Ef9upSlARUSFhaBYwTjeqQ.png" /></figure><p>XGBoost is a powerful and popular machine learning algorithm that uses an ensemble of decision trees to improve the predictive performance of a model. In this article, we’ll see how to use XGBoost to train and tune a model using the Titanic dataset, which contains information about the passengers of the Titanic, such as their age, sex, and fare class, and is often used to train machine learning models to predict whether a passenger survived the sinking of the ship or not.</p><h3>Preparing the data</h3><p>First, we need to import the necessary Python libraries and load the Titanic data into a DataFrame. We&#39;ll use the pandas library to load and manipulate the data.</p><pre>import pandas as pd<br>from sklearn.model_selection import train_test_split<br><br># Load the Titanic data into a Pandas DataFrame<br>df = pd.read_csv(&#39;titanic.csv&#39;)<br><br># Print the first few rows of the DataFrame<br>print(df.head())</pre><pre>    PassengerId  Survived  Pclass ...     Fare Cabin  Embarked<br>0            1         0       3  ...   7.2500   NaN         S<br>1            2         1       1  ...  71.2833   C85         C<br>2            3         1       3  ...   7.9250   NaN         S<br>3            4         1       1  ...  53.1000  C123         S<br>4            5         0       3  ...   8.0500   NaN         S</pre><p>Next, we need to select the features we want to use to train the model and the target variable. In this case, we’ll use the Age, Sex, Pclass ,Fare and Embarkedcolumns as features and the Survived column as the target variable. Then, we&#39;ll split the data into training and test sets using the train_test_split() function.</p><ol><li>Handling missing values: The Titanic dataset may have missing values in some of the columns. These missing values can be handled by imputing them with a suitable replacement value, such as the column mean or median.</li><li>Encoding categorical variables: The dataset may contain columns with categorical values, such as the gender of a passenger (male or female). These values need to be encoded as numerical values in order for the model to be able to handle them. This can be done using techniques such as one-hot encoding.</li><li>Normalizing numerical values: The numerical values in the dataset may have different scales, such as the age of a passenger (measured in years) and the fare paid for the ticket (measured in dollars). This can cause some algorithms to weigh certain columns more heavily than others, which can affect the model’s performance. Normalizing the values to have a common scale can address this issue.</li></ol><pre># One-hot encode Pclass feature<br>pclass_dummies = pd.get_dummies(df[&quot;Pclass&quot;], prefix=&quot;Pclass&quot;)<br># Drop original Pclass column and add one-hot encoded columns<br>df = df.drop(&quot;Pclass&quot;, axis=1)<br>df = pd.concat([df, pclass_dummies], axis=1)<br><br># One-hot encode Embarked feature<br>embarked_dummies = pd.get_dummies(df[&quot;Embarked&quot;], prefix=&quot;Embarked&quot;)<br># Drop original Embarked column and add one-hot encoded columns<br>df = df.drop(&quot;Embarked&quot;, axis=1)<br>df = pd.concat([df, embarked_dummies], axis=1)<br><br># handle missing values<br>df[&#39;Age&#39;] = df[&#39;Age&#39;].fillna(df[&#39;Age&#39;].median())<br><br># encode categorical variables<br>df[&#39;Sex&#39;] = df[&#39;Sex&#39;].map({&#39;male&#39;: 0, &#39;female&#39;: 1})<br><br># normalize numerical values<br>df[&#39;Age&#39;] = (df[&#39;Age&#39;] - df[&#39;Age&#39;].mean()) / df[&#39;Age&#39;].std()<br>df[&#39;Fare&#39;] = (df[&#39;Fare&#39;] - df[&#39;Fare&#39;].mean()) / df[&#39;Fare&#39;].std()<br><br><br>#Select the features we want to use to train the model<br>X = df[[&#39;Age&#39;, &#39;Sex&#39;, &#39;Fare&#39;,&#39;Pclass_1&#39;, &#39;Pclass_2&#39;, &#39;Pclass_3&#39;,<br>       &#39;Embarked_C&#39;, &#39;Embarked_Q&#39;, &#39;Embarked_S&#39;]]<br><br># Print the unique values in the sex column<br>print(X[&#39;Sex&#39;].unique())<br><br># Select the target variable<br>y = df[&#39;Survived&#39;]<br><br># Split the data into training and test sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><p>Here you can find the titanic dataset <a href="https://www.kaggle.com/competitions/titanic/data">https://www.kaggle.com/competitions/titanic/data</a></p><h3>Training an XGBoost model</h3><p>Now that we have prepared the data, we can train an XGBoost model using the xgboost library. First, we need to import the library and create an XGBClassifier object. Then, we can train the model using the fit() method, passing it the training data and the target variable. For the first training process, we will use the default parameter values.</p><pre># Import the XGBoost library<br>import xgboost as xgb<br><br># Create an XGBoost model<br>model = xgb.XGBClassifier()<br><br># Train the model on the training data<br>model.fit(X_train, y_train)</pre><p>Once the model is trained, we can use it to make predictions on the test data and evaluate its performance using an appropriate metric, such as accuracy or F1 score. For this, we can use the accuracy_score() and f1_score() functions from the sklearn library to evaluate the model&#39;s performance.</p><pre>from sklearn.metrics import accuracy_score, f1_score<br><br># Use the model to make predictions on the test data<br>y_pred = model.predict(X_test)<br><br># Evaluate the model&#39;s performance using accuracy<br>acc = accuracy_score(y_test, y_pred)<br>print(&#39;Accuracy:&#39;, acc)<br># Accuracy: 0.7988826815642458<br><br># Evaluate the model&#39;s performance using F1 score<br>f1 = f1_score(y_test, y_pred)<br>print(&#39;F1 score:&#39;, f1)<br># F1 score: 0.7567567567567567</pre><p>The accuracy_score() calculates the proportion of correct predictions made by the model and returns it as a decimal value between 0 and 1. The f1_score() function calculates the weighted average of the precision and recall of the model and returns it as a decimal value between 0 and 1. Higher values for both metrics indicate better-performing models.</p><h3>Why F1 Score?</h3><p>Precision is the fraction of true positives (i.e., the number of passengers who were correctly predicted to have survived) out of all positive predictions (i.e., the total number of passengers predicted to have survived). High precision means that the model is not predicting too many passengers to have survived when they actually did not, which is important because false positives (i.e., passengers who were predicted to have survived but actually did not) can lead to incorrect conclusions.</p><p>Recall is the fraction of true positives (i.e., the number of passengers who were correctly predicted to have survived) out of all actual positive cases (i.e., the total number of passengers who actually survived). High recall means that the model is correctly predicting most of the passengers who actually survived, which is important because false negatives (i.e., passengers who were predicted to not have survived but actually did) can lead to missed opportunities.</p><p>The F1 score is the harmonic mean of the precision and recall, which means that it considers both of these metrics equally.</p><h3>Tuning hyperparameters</h3><p>Tuning hyperparameters is the process of finding the optimal values of these parameters that result in the best performance of the model on a given dataset.</p><p>For example, suppose you want to tune the following parameters for an XGBoost classifier:</p><ul><li>max_depth: This parameter sets the maximum depth of the tree. Increasing the value of max_depth can lead to more complex and accurate models, but can also increase the risk of overfitting.</li><li>learning_rate: This parameter sets the learning rate for the gradient boosting algorithm. Increasing the learning rate can lead to faster convergence, but can also lead to unstable models.</li><li>n_estimators: This parameter sets the number of trees in the model. Increasing the value of n_estimators can lead to more accurate models, but can also increase the computational cost.</li><li>gamma: This parameter sets the minimum loss reduction required to make a further partition on a leaf node of the tree. Increasing the value of gamma can lead to more conservative models, which can reduce the risk of overfitting.</li><li>subsample: This parameter sets the fraction of observations to be used for each tree. Increasing the value of subsample can lead to more accurate models, but can also increase the computational cost.</li></ul><p>GridSearchCV performs a grid search over a specified range of hyperparameter values and finds the combination that results in the best performance.</p><pre>from xgboost import XGBClassifier<br>from sklearn.model_selection import GridSearchCV<br><br># Create an XGBoost model<br>model = XGBClassifier()<br><br># Define the grid of hyperparameters we want to search<br>hyperparameters = {<br>    &#39;max_depth&#39;: [3,4,5,6,7],<br>    &#39;learning_rate&#39;: [0.1, 0.3, 0.5],<br>    &#39;n_estimators&#39;: [100, 200,300],<br>    &#39;gamma&#39;: [0,0.1,0.3, 1],<br>    &#39;subsample&#39;: [0.5,0.7, 1.0]<br>}<br><br># Use GridSearchCV to tune the hyperparameters of the model<br>model = GridSearchCV(model, hyperparameters, cv=3, scoring=&#39;f1&#39;)<br>model.fit(X_train, y_train)</pre><p>Here you can learn all xgboost parameters: <a href="https://xgboost.readthedocs.io/en/stable/parameter.html">https://xgboost.readthedocs.io/en/stable/parameter.html</a></p><p>Once the grid search is completed, we can access the best-performing model using the best_estimator_ attribute and use it to make predictions on the test data.</p><pre># Print the best combination of parameters<br>print(model.best_params_)</pre><pre>{&#39;gamma&#39;: 1, &#39;learning_rate&#39;: 0.1, &#39;max_depth&#39;: 5, &#39;n_estimators&#39;: 200, &#39;subsample&#39;: 0.5}</pre><pre># Use the best-performing model to make predictions on the test data<br>y_pred = model.best_estimator_.predict(X_test)<br><br># Evaluate the model&#39;s performance using F1 score<br>f1 = f1_score(y_test, y_pred)<br>print(&#39;F1 score:&#39;, f1)<br># F1 score: 0.7832167832167832</pre><p>Using a hyperparameter technique improved our model F1 score compared to a default parameter model without any tunning process.</p><h3>Conclusion</h3><p>In this article, we saw how to use XGBoost to train and tune a model using the Titanic dataset. We prepared the data, trained a basic XGBoost model, and used GridSearchCV to tune the hyperparameters of the model. The resulting model achieved an F1 score of 0.783 on the test data, which indicates that it was able to make accurate predictions about whether a passenger survived the sinking of the Titanic or not.</p><p>There are many ways in which the performance of the model can be improved further. For example, we could try using more features from the dataset, such as the number of siblings and parents they had on board, or we could try using different evaluation metrics, such as precision or recall. Additionally, we could try using different ensemble methods, such as random forests or gradient-boosting machines, to improve the predictive power of the model.</p><p>If you want to apply the techniques shown in this article to your own datasets and problems, you can use the code provided as a starting point and experiment with different hyperparameters and features to see how they affect the performance of the model. With some practice and tuning, you’ll be able to use XGBoost to improve the accuracy of your predictions and solve your own machine-learning problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae9cf1a63bbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>