<?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 Fagbuyi Temitope Emmanuel on Medium]]></title>
        <description><![CDATA[Stories by Fagbuyi Temitope Emmanuel on Medium]]></description>
        <link>https://medium.com/@tofag?source=rss-4e93c4cff640------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sVsFaWXhn_KwiQxZVpg0Mg.jpeg</url>
            <title>Stories by Fagbuyi Temitope Emmanuel on Medium</title>
            <link>https://medium.com/@tofag?source=rss-4e93c4cff640------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 09:02:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tofag/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[A Predictive Linear Model for Aerosol Data Analysis]]></title>
            <link>https://blog.devgenius.io/a-predictive-model-for-aerosol-data-analysis-8f9ab1a463a8?source=rss-4e93c4cff640------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f9ab1a463a8</guid>
            <category><![CDATA[data-modelling]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Fagbuyi Temitope Emmanuel]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 11:36:21 GMT</pubDate>
            <atom:updated>2024-12-31T17:57:26.774Z</atom:updated>
            <content:encoded><![CDATA[<p>As an individual with a background in environmental science, understanding atmospheric phenomena remains an interesting preoccupation.</p><p>Aerosol Optical Depth (AOD), a measure of the degree to which aerosols ((tiny particles in the atmosphere) prevent sunlight from reaching the Earth’s surface, is a vital parameter in atmospheric science. Accurate analysis and prediction of AOD can aid in monitoring pollution levels, understanding climatic shifts, and planning environmental interventions.</p><p>In this project, I developed a predictive model tailored for aerosol data analysis of the <a href="https://open.africa/dataset/9cef5972-8278-4669-962a-3d92f959d243/resource/9fd13a70-c726-4540-8293-4e66da1f51c6/download/africa_data_complete.csv">Africa Climate Air Quality Dataset</a>. Using Python, I covered (or tried to) every step of the process, from automated data ingestion to cleaning, wrangling, and modeling.</p><p>By the end of this guide, I hope you’ll not only understand how to streamline workflows for complex environmental data but also learn how to build robust predictive models that can drive impactful decisions in atmospheric studies.</p><p>The full code for this project is <a href="https://github.com/Tofag-py/aerosol-optical-depth-pipeline.git">here</a>.</p><h4>Objective</h4><p>My goal is to:</p><ol><li>Download, process, and prepare aerosol data for analysis.</li><li>Develop a robust machine-learning pipeline to predict Aerosol Optical Depth Mean (AOD) using environmental features.</li><li>Evaluate the model and visualize its performance.</li><li>Know if my model is correct and how next to improve it.</li></ol><h3>1. Understanding the Data</h3><p>Predictive modeling relies heavily on understanding the dataset you’re working with. In this case, I analyzed aerosol optical depth (AOD) data, which measures how aerosols prevent sunlight from reaching the Earth’s surface.</p><h3>Key Features in the Dataset:</h3><ul><li><strong>Latitude and Longitude</strong>: Spatial coordinates representing specific geographical locations.</li><li><strong>Aerosol Optical Depth Metrics:</strong></li><li><strong>Min, Mean, and Max</strong>: Describe the range and average levels of aerosol concentrations at a given location.</li><li><strong>Std (Standard Deviation)</strong>: Indicates the variability in aerosol concentrations over time.</li><li><strong>Temporal Variables</strong>:</li><li><strong>Year</strong>: Identifies the year of observation, useful for detecting long-term trends.</li><li><strong>Month Number</strong>: The month of observation, helpful in identifying seasonal patterns.</li></ul><h4>Example Data:</h4><p>The following picture show a sample from the dataset:</p><figure><img alt="A captured Excel sheet containing the first 10 lines of the data" src="https://cdn-images-1.medium.com/max/1024/1*YxaouxExBmCNA60_QqoUVw.png" /><figcaption>First 10 rows of the dataset.</figcaption></figure><p>This data allows us to explore spatial and temporal variations in aerosol concentrations.</p><p>In this project, I will predicting the <strong>AOD_Mean</strong> feature because it provides a concise representation of aerosol concentration levels.</p><h3>2. Preparing the Workflow</h3><p>Let’s break this workflow into two key components: <strong>data ingestion, Exploratory Data Analysis </strong>and M<strong>odeling.</strong></p><h3>Part 1: Data Ingestion</h3><p>To streamline and automate the ingestion process for the aerosol dataset, I designed a workflow that downloads the data, cleans it, and prepares it for analysis. The Python script data_ingestion.py encapsulates this workflow. Here&#39;s an overview:</p><h4>1. Automating Data Download</h4><p>The first step is to fetch the dataset from an external URL. This is automated using the requests library and Prefect, a Python library for workflow orchestration.</p><pre>@task<br>def download_data(url: str, file_path: str):<br>    try:<br>        print(f&quot;Starting download from {url}&quot;)<br>        response = requests.get(url)<br>        response.raise_for_status()  # Check for HTTP errors        <br># Ensure the directory exists<br>        os.makedirs(os.path.dirname(file_path), exist_ok=True)<br># Write the content to the specified file<br>        with open(file_path, &quot;wb&quot;) as f:<br>            f.write(response.content)<br>        print(f&quot;Data successfully downloaded and saved to {file_path}&quot;)<br>    except requests.exceptions.RequestException as e:<br>        print(f&quot;Failed to download data: {e}&quot;)<br>        raise<br>    return file_path</pre><p><strong>Key Features</strong></p><ul><li>Validates the URL and checks for any issues in downloading.</li><li>Ensures the target directory exists before saving the file.</li><li>Returns the path of the downloaded file for subsequent tasks.</li></ul><h4>2. Loading Data into a DataFrame</h4><p>After downloading the dataset, the next step is to load it into a Pandas DataFrame for further processing.</p><pre>@task<br>def make_df(file_path: str) -&gt; pd.DataFrame:<br>    df = pd.read_csv(file_path)<br>    return df</pre><p><strong>Why?</strong></p><ul><li>A DataFrame is ideal for handling tabular data and is essential for cleaning, preprocessing, and analysis.</li></ul><h4>3. Renaming Columns for Consistency</h4><p>Renaming columns improves clarity and simplifies future referencing.</p><pre>@task<br>def rename_columns(data: pd.DataFrame) -&gt; pd.DataFrame:<br>    data.rename(columns={<br>        &quot;Aerosol_Optical_Depth_Land_Ocean_Mean_Min&quot;: &quot;Aerosol_OD_Min&quot;,<br>        &quot;Aerosol_Optical_Depth_Land_Ocean_Mean_Mean&quot;: &quot;Aerosol_OD_Mean&quot;,<br>        &quot;Aerosol_Optical_Depth_Land_Ocean_Mean_Max&quot;: &quot;Aerosol_OD_Max&quot;,<br>        &quot;Aerosol_Optical_Depth_Land_Ocean_Mean_Std&quot;: &quot;Aerosol_OD_Std&quot;<br>    }, inplace=True)<br>    return data</pre><p><strong>Key Changes:</strong></p><ul><li>Simplified column names: For instance, &quot;Aerosol_Optical_Depth_Land_Ocean_Mean_Min&quot; becomes &quot;Aerosol_OD_Min&quot;.</li><li>Ensures uniform naming for better readability.</li></ul><h4>4. Saving the Cleaned Data</h4><p>The cleaned DataFrame is saved to a new CSV file, ready for subsequent analysis or modeling.</p><pre>@task<br>def save_renamed_data(data: pd.DataFrame, renamed_csv_path: str) -&gt; str:<br>    data.to_csv(renamed_csv_path, index=False)  # Avoid saving the index<br>    return renamed_csv_path</pre><p><strong>Why?</strong></p><ul><li>Saves the transformed data for reuse without re-running the entire ingestion workflow.</li></ul><h4>5. Orchestrating the Workflow</h4><p>The entire data ingestion pipeline is orchestrated with Prefect’s @flow decorator, ensuring tasks execute in sequence.</p><pre>@flow<br>def main_flow():<br>    url = &quot;https://open.africa/dataset/9cef5972-8278-4669-962a-3d92f959d243/resource/9fd13a70-c726-4540-8293-4e66da1f51c6/download/africa_data_complete.csv&quot;<br>    local_csv_path = &quot;data/africa_dataset.csv&quot;<br>    renamed_csv_path = &quot;data/africa_dataset_renamed.csv&quot;<br>    # Download the data<br>    file = download_data(url, local_csv_path)<br>    # Load the data into a DataFrame<br>    DataF = make_df(file)<br>    # Rename the columns<br>    renamed_df = rename_columns(DataF)<br>    # Save the renamed data<br>    saved_file_path = save_renamed_data(renamed_df, renamed_csv_path)<br>    print(f&quot;Renamed data saved to {saved_file_path}&quot;)<br>    return saved_file_path</pre><h4>Execution</h4><p>To run the workflow, execute the script:</p><pre>if __name__ == &#39;__main__&#39;:<br>    main_flow()</pre><h4>Output</h4><ul><li>The raw dataset is downloaded to data/africa_dataset.csv.</li><li>The cleaned and renamed dataset is saved as data/africa_dataset_renamed.csv.</li></ul><h3>Part 2: Data Analysis</h3><p>To develop a predictive model, preparing the data through preprocessing and exploratory analysis is critical.</p><h4>Goals for Data Preparation:</h4><p>By cleaning and understanding the data, we aim to:</p><ul><li>Enhance the predictive accuracy of the model.</li><li>Gain insights into the factors driving aerosol variations.</li><li>Lay a solid foundation for feature engineering and model development.</li></ul><h4>Data Preprocessing:</h4><ul><li><strong>Handling Missing Values</strong>: Check for any missing data points in the columns. For instance, if AOD values are missing for a location, I need to impute or remove them to avoid bias. In this case, no field is missing data points.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*9TS8V5V2ahtnv-ti5oLJxQ.png" /></figure><ul><li><strong>Encoding Temporal Data</strong>: Transform the month number into seasonal categories (e.g., Winter, Spring) to capture cyclic patterns more effectively. This was done later in the data cleaning function.</li></ul><p><strong>Exploratory Data Analysis (EDA):</strong></p><ul><li><strong>Spatial Analysis</strong>: Visualize the geographical distribution of AOD mean levels using scatterplots or heatmaps. Identify areas with consistently high or low AOD values.</li></ul><pre>fig = px.scatter_mapbox(<br>    df,<br>    lat=&quot;latitude&quot;,<br>    lon=&quot;longitude&quot;,<br>    width=600,<br>    height=600,<br>    color=&quot;Aerosol_OD_Mean&quot;,<br>    hover_data=[&quot;Aerosol_OD_Min&quot;, &quot;Aerosol_OD_Mean&quot;, &quot;Aerosol_OD_Max&quot;]<br>)</pre><pre>fig.update_layout(mapbox_style=&quot;open-street-map&quot;)<br>fig.show()</pre><p>The dataset keeps breaking my Jupyter Notebook instance, so this code excerpt randomizes and restricts the data sample to 10,000.</p><pre># Restrict to a random sample of 10,000 rows (or any smaller number)<br>sampled_df = df.sample(n=10000, random_state=42)</pre><pre>fig = px.scatter_mapbox(<br>    sampled_df,  # Use sampled DataFrame<br>    lat=&quot;latitude&quot;,<br>    lon=&quot;longitude&quot;,<br>    width=600,<br>    height=600,<br>    color=&quot;Aerosol_OD_Mean&quot;,<br>    hover_data=[&quot;Aerosol_OD_Min&quot;, &quot;Aerosol_OD_Mean&quot;, &quot;Aerosol_OD_Max&quot;],<br>)</pre><pre>fig.update_layout(mapbox_style=&quot;open-street-map&quot;)</pre><pre>fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YxXHBSzz8g1wGQhNfDsadA.png" /><figcaption>Heatmap of the randomized sample data</figcaption></figure><p>The scatter map reveals clusters of Aerosol Optical Depth (AOD) values, with higher concentrations (orange-yellow) indicating denser aerosols, likely from pollution or natural sources like dust storms. Lower values (purple) suggest clearer atmospheric conditions. The patterns suggest geographical or environmental influences, such as urban areas or deserts. Outliers may indicate unusual events like wildfires or industrial activity. Further analysis with geographical overlays or temporal trends could provide deeper insights.</p><p>Since the focus of this project is not on analyzing the dataset, I wouldn’t focus on the EDA but derive enough insight to clean my data. For now, this is removing Outliers to increase the correctness of our model.</p><ul><li><strong>Correlations</strong>: Investigate the relationships between AOD metrics and variability (Std). Are regions with high mean values also highly variable</li></ul><pre>corr = df.select_dtypes(&quot;number&quot;).drop(columns=&quot;Aerosol_OD_Mean&quot;).corr()<br>sns.heatmap(corr)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tQzOsbaljc3r0znr" /></figure><p>The heatmap reveals strong correlations among the “Aerosol_OD_Min,” “Aerosol_OD_Max,” and “Aerosol_OD_Std” features, indicating multicollinearity. Hence, these columns will be removed in the cleaning to avoid redundancy. Other features like “latitude,” “longitude,” and “month_number” show low correlations with one another, suggesting they capture independent aspects of the data. Although the feature “year” shows minimal correlation, temporal columns will be removed.</p><ul><li><strong>Distributions</strong>: Plot histograms or box plots for AOD values to understand their spread and detect outliers.</li><li><strong>Quantile Analysis: </strong>To analyze the distribution of aerosol optical depth mean metrics, I plotted the quantiles.</li></ul><pre># Generate all quantiles from 0 to 1 with a step of 0.01<br>quantiles = df[&quot;Aerosol_OD_Mean&quot;].quantile([i / 100 for i in range(101)])</pre><pre># Print the results<br>print(quantiles)</pre><pre>quantiles.plot(kind=&#39;line&#39;, title=&quot;Quantiles of Aerosol_OD_Mean&quot;)<br>plt.xlabel(&quot;Quantile&quot;)<br>plt.ylabel(&quot;Value&quot;)<br>plt.grid()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*W9Aeq2bW_jEErfbD7IRB3Q.png" /><figcaption>Quantile distribution of the Aerosol Mean</figcaption></figure><p>From the image above, the quantile plot of “Aerosol_OD_Mean” shows a highly skewed distribution.</p><ul><li>The values below the 20th percentile exhibit a steep negative drop, indicating outliers or extreme values on the lower end.</li><li>The middle range (20th to 80th percentile) shows a flat plateau, suggesting many values are concentrated near 0.</li><li>Beyond the 90th percentile, there is another sharp increase, highlighting the presence of extremely positive outliers.</li></ul><p>This skewness and the presence of outliers validate the need to filter out data based on quantiles for better statistical modeling. For this project, I limited the values to between the 10th and 90th percentiles.</p><h4>Data Quality and Structure</h4><p>I did the final check for data quality and structure by checking the unique values and the duplicates.</p><pre>df.select_dtypes(&quot;number&quot;).nunique()</pre><pre>df.duplicated().sum()</pre><p>No duplicates, and the nunique method cemented the need to do away with the temporal fields.</p><p>Phew, now Data preprocessing is done.</p><h3>Part 3: Building a Predictive Model for Aerosol Optical Depth (AOD)</h3><p>In this section, I’ll take the cleaned and processed aerosol data and build a predictive model to estimate <strong>Aerosol Optical Depth (AOD)</strong>. The goal is to apply machine learning techniques to create a robust model, evaluate its performance, and visualize its results. We will use a combination of <strong>Ridge regression</strong>, a regularized version of linear regression, and other preprocessing techniques such as <strong>one-hot encoding</strong> and <strong>imputation</strong>.</p><h3>1. Setting Up the Environment</h3><p>To begin, we need to import the necessary libraries. These include <strong>scikit-learn</strong> for machine learning, <strong>pandas</strong> for data manipulation, <strong>matplotlib</strong> and <strong>seaborn</strong> for visualization, and <strong>Prefect</strong> for task orchestration.</p><pre>import pandas as pd<br>from sklearn.impute import SimpleImputer<br>from sklearn.linear_model import Ridge  # noqa F401<br>from sklearn.metrics import mean_absolute_error<br>from sklearn.pipeline import make_pipeline, Pipeline<br>from sklearn.utils.validation import check_is_fitted<br>from sklearn.compose import ColumnTransformer<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.metrics import mean_squared_error, r2_score<br>import seaborn as sns<br>import plotly.express as px<br>from category_encoders import OneHotEncoder<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split<br>from prefect import task, flow<br>from ingestion import main_flow<br>from prefect.logging import get_run_logger</pre><p>These libraries will allow us to:</p><ul><li><strong>Handle data</strong>: Pandas is used for managing dataframes, while <strong>plotly</strong> and <strong>matplotlib</strong> assist with creating visualizations.</li><li><strong>Modeling</strong>: Scikit-learn provides tools for data preprocessing, machine learning models, and evaluation metrics.</li><li><strong>Task orchestration</strong>: Prefect helps in organizing the workflow of data ingestion, transformation, and modeling, ensuring that everything runs smoothly.</li></ul><h3>2. Logging and Monitoring</h3><p>Before going into data processing, I set up logging to track the flow and capture insights throughout the task execution. This is done using the <strong>Prefect</strong> logging system, which provides the ability to log messages at different levels (INFO, DEBUG, ERROR, etc.).</p><pre>@task()<br>def logger_task():<br>    logger = get_run_logger()<br>    logger.info(&quot;INFO level log message from a task.&quot;)<br>    logger.debug(&quot;DEBUG level log message from a task.&quot;)</pre><pre>@flow()<br>def logger_flow():<br>    logger = get_run_logger()<br>    logger.info(&quot;INFO level log message.&quot;)<br>    logger.debug(&quot;DEBUG level log message.&quot;)<br>    logger.error(&quot;ERROR level log message.&quot;)<br>    logger.critical(&quot;CRITICAL level log message.&quot;)<br>    logger_task()</pre><p>Here, the logger_task and logger_flow functions emit logs for tracking the model building process. Logging allows you to monitor progress, debug errors, and ensure the flow executes as expected.</p><h3>3. Data Preparation and Wrangling</h3><p>Once the data is ingested, the next step is to clean and transform it. In the wrangle() function, I clean the data by removing outliers, dealing with multicollinearity, and preparing new features. This helps to improve the model’s performance by ensuring that the data fed into the model is consistent and of high quality.</p><p>Key steps include:</p><ul><li><strong>Removing Outliers</strong>: We remove values outside the 10th and 90th percentiles to avoid skewing the model’s predictions.</li><li><strong>Removing Multicollinear Features</strong>: Columns that are highly correlated (e.g., Aerosol_OD_Min, Aerosol_OD_Max, Aerosol_OD_Std) are dropped.</li><li><strong>Feature Engineering</strong>: A new season feature is created by categorizing the month_number into seasonal groups like Winter, Spring, Summer, and Fall.</li></ul><pre>def wrangle(df: pd.DataFrame):<br>    lower_quantile = df[&quot;Aerosol_OD_Mean&quot;].quantile(0.1)<br>    upper_quantile = df[&quot;Aerosol_OD_Mean&quot;].quantile(0.9)<br>    <br>    df = df[<br>        (df[&quot;Aerosol_OD_Mean&quot;] &gt;= lower_quantile) &amp; <br>        (df[&quot;Aerosol_OD_Mean&quot;] &lt;= upper_quantile)<br>    ].copy()  <br>    <br>    df.drop(columns=[&quot;Aerosol_OD_Min&quot;, &quot;Aerosol_OD_Max&quot;, &quot;Aerosol_OD_Std&quot;], inplace=True)<br>    <br>    df.loc[:, &#39;season&#39;] = df[&#39;month_number&#39;].apply(lambda month: <br>        &#39;Winter&#39; if month in [12, 1, 2] else <br>        &#39;Spring&#39; if month in [3, 4, 5] else <br>        &#39;Summer&#39; if month in [6, 7, 8] else <br>        &#39;Fall&#39;<br>    )<br>    <br>    df.drop(columns=[&quot;month_number&quot;, &quot;year&quot;], inplace=True)<br>    <br>    return df</pre><p>By using these transformations, I improve the quality of the features, ensuring that the model is trained on relevant data without extraneous or redundant information.</p><h3>4. Splitting the Dataset</h3><p>Before training the model, I split the dataset into <strong>training</strong> and <strong>testing</strong> sets. This allowed me to evaluate the model on unseen data and get a true sense of how well it generalizes.</p><pre>@task<br>def split_dataset(df: pd.DataFrame):<br>    X = df.drop(columns=[&quot;Aerosol_OD_Mean&quot;])<br>    y = df[&quot;Aerosol_OD_Mean&quot;]<br>    <br>    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br>    <br>    return [X_train, X_test, y_train, y_test]</pre><p>I used <strong>train_test_split</strong> from scikit-learn to split the data. 80% of the data is used for training, while 20% is kept for testing the model.</p><p>The image below shows the shape of each of the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ljM3mErDT2bVHqZuaLzRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*CUpYx4QuOeoXPZYYxvAcbQ.png" /><figcaption>Baseline MAE</figcaption></figure><h3>5. Model Training and Evaluation</h3><p>The next step is to create the <strong>machine learning pipeline</strong>, which includes preprocessing (imputing missing values, one-hot encoding categorical features) and the model itself (Ridge regression). The pipeline ensures that all the steps are executed in a defined order, making it easier to manage and deploy.</p><h4>Building the Model Pipeline:</h4><pre>@task<br>def model(X_train, y_train):<br>    model = make_pipeline(<br>        OneHotEncoder(use_cat_names=True),<br>        SimpleImputer(strategy=&quot;mean&quot;),<br>        Ridge()<br>    )<br>    <br>    model.fit(X_train, y_train)<br>    print(f&quot;Model score: {model.score(X_train, y_train):.4f}&quot;)<br>    <br>    return model</pre><p>Here, I used:</p><ul><li><strong>OneHotEncoder</strong>: To encode categorical variables such as season.</li><li><strong>SimpleImputer</strong>: To handle any missing values by filling them with the mean of the column.</li><li><strong>Ridge</strong>: A regularized linear regression model that helps prevent overfitting, especially when dealing with correlated features.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*bEEt8fqaRQ6Y90dBzT_NzQ.png" /></figure><p>Once the model is trained, I evaluate its performance by measuring its accuracy on the training set using .score().</p><pre>print(f&quot;Model score: {model.score(X_train, y_train):.4f}&quot;)</pre><pre>Model score: 0.3155</pre><h4>Making Predictions and Evaluating the Model:</h4><p>Once the model is trained, I predicted the target variable (Aerosol_OD_Mean) on the test set and evaluate the model using various metrics, including <strong>Mean Absolute Error (MAE)</strong>, <strong>Root Mean Squared Error (RMSE)</strong>, and <strong>R²</strong> (coefficient of determination). These metrics will help assess how well the model performs.</p><pre>@task<br>def evaluate_model(y_test, y_test_pred):<br>    mae = mean_absolute_error(y_test, y_test_pred)<br>    rmse = mean_squared_error(y_test, y_test_pred, squared=False)<br>    r2 = r2_score(y_test, y_test_pred)<br>    <br>    print(f&quot;Test MAE: {mae:.4f}&quot;)<br>    print(f&quot;Test RMSE: {rmse:.4f}&quot;)<br>    print(f&quot;Test R²: {r2:.4f}&quot;)<br>    <br>    return {&quot;MAE&quot;: mae, &quot;RMSE&quot;: rmse, &quot;R²&quot;: r2}</pre><p>We calculate <strong>MAE</strong> to understand the average error in the predictions, <strong>RMSE</strong> to measure the spread of the errors, and <strong>R²</strong> to assess the proportion of variance in the target variable explained by the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*SZjFuQlcNO6rcUb6cd1_rQ.png" /></figure><h3>6. Feature Importance</h3><p>Understanding which features contribute the most to the model’s predictions is crucial. In Ridge regression, we can access the model’s coefficients to identify feature importance.</p><pre>@task<br>def communicate_result(model):<br>    coefficients = model.named_steps[&quot;ridge&quot;].coef_<br>    features = model.named_steps[&quot;onehotencoder&quot;].get_feature_names_out()<br>    <br>    feat_imp = pd.Series(coefficients, index=features)<br>    feat_imp = feat_imp.reindex(feat_imp.abs().sort_values().index)<br>    <br>    formula = &quot;y = &quot;<br>    for feature, coef in zip(feat_imp.index, feat_imp):<br>        if coef &gt;= 0:<br>            formula += f&quot; + ({coef:.4f} * {feature})&quot;<br>        else:<br>            formula += f&quot; - ({abs(coef):.4f} * {feature})&quot;<br>    print(&quot;Model Formula:&quot;, formula)<br>    <br>    feat_imp_df = feat_imp.reset_index()<br>    feat_imp_df.columns = [&quot;Feature&quot;, &quot;Coefficient&quot;]<br>    <br>    print(&quot;Feature Importance:&quot;)<br>    print(feat_imp_df)<br>    return feat_imp_df</pre><p>Here, I access the coefficients of the <strong>Ridge model</strong> to determine which features contribute positively or negatively to the prediction. We generate a formula that represents the model’s behavior and also visualize the feature importance in a <strong>DataFrame</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*ZXemVmIKqvFtYvfW4ZMh3A.png" /></figure><p>And here is the feature importance explanation:<br><strong>Longitude</strong>:</p><ul><li>With a Coefficient of <strong>-0.8963, </strong>Longitude has a small but <strong>negative</strong> influence on the prediction. As longitude increases, <strong>Aerosol_OD_Mean</strong> decreases, but its effect is relatively minor compared to other features.</li></ul><p><strong>Latitude</strong>:</p><ul><li>Latitude has a <strong>strong negative</strong> influence on <strong>Aerosol_OD_Mean</strong>. It has a Coefficient of <strong>-109.98. </strong>Hence, as latitude increases, <strong>Aerosol_OD_Mean</strong> decreases, indicating that locations farther from the equator have lower aerosol levels.</li></ul><p><strong>Season (Spring)</strong>:</p><ul><li>Spring has a moderate negative influence on the target variable. With a coefficient of <strong>-12.68, </strong>and<strong> </strong>compared to other seasons, Spring tends to lower <strong>Aerosol_OD_Mean. </strong>However, it’s<strong> </strong>impact is not as significant as Summer or Fall.</li></ul><p><strong>Season (Winter)</strong>:</p><ul><li>Coefficient = <strong>58.25.</strong></li><li>Winter has a <strong>moderate positive</strong> influence on <strong>Aerosol_OD_Mean.</strong> This suggests that the Aerosol Optical Depth tends to increase in Winter. However, the effect is not as strong as Fall or Summer.</li></ul><p><strong>Season (Fall)</strong>:</p><ul><li>With a significant Coefficient of <strong>248.51, </strong>Fall has the <strong>strongest positive</strong> impact on <strong>Aerosol_OD_Mean</strong>, meaning that when observations occur in Fall, <strong>Aerosol_OD_Mean</strong> tends to be at its highest value.</li></ul><p><strong>Season (Summer)</strong>:</p><ul><li>Summer has the <strong>strongest negative</strong> effect on <strong>Aerosol_OD_Mean</strong>, with a much larger negative coefficient (<strong>-294.08) </strong>than Spring. Locations in Summer are predicted to have much lower aerosol levels compared to other seasons.</li></ul><h4><strong>Model formular:</strong></h4><p><strong>y=−(0.8963×longitude)−(12.6797×season_Spring)+(58.2488×season_Winter)−(109.9788×latitude)+(248.5084×season_Fall)−(294.0775×season_Summer)</strong></p><p><strong>Interpretation of the Formula:</strong></p><ul><li><strong>Longitude</strong>: has a negative coefficient of <strong>-0.8963</strong> which means that as the longitude increases, the <strong>Aerosol_OD_Mean</strong> is expected to decrease. As the <strong>longitude</strong> increases, the predicted <strong>Aerosol_OD_Mean</strong> decreases slightly by <strong>0.8963</strong>.</li><li><strong>Latitude</strong>: A negative coefficient of <strong>-109.9788</strong> suggests that an increase in latitude towards the north reduces the <strong>Aerosol_OD_Mean</strong>. This implies that regions further north might have lower <strong>Aerosol_OD_Mean</strong> values.</li><li><strong>Season (Summer)</strong>: has the largest negative coefficient (in the context of this project, will be our baseline season) of <strong>-294.0775</strong> suggests that Summer is associated with the <strong>lowest</strong> values of <strong>Aerosol_OD_Mean</strong> among all seasons. An increase in <strong>Summer</strong> corresponds to a large decrease in <strong>Aerosol_OD_Mean</strong>.</li><li><strong>Season (Spring)</strong>: has a negative coefficient of <strong>-12.6797.</strong> This indicates that when the observation is in <strong>Spring</strong>, the predicted <strong>Aerosol_OD_Mean</strong> decreases by around <strong>12.68 </strong>compared to the baseline season. This suggests that Spring is associated with lower <strong>Aerosol_OD_Mean</strong> than other seasons.</li><li><strong>Season (Winter)</strong>: A positive coefficient of <strong>58.2488.</strong> This indicates that Winter is associated with higher <strong>Aerosol_OD_Mean</strong> values. When the observation is in <strong>Winter</strong>, the predicted <strong>Aerosol_OD_Mean</strong> increases by about <strong>58.25</strong>.</li><li><strong>Season (Fall)</strong>: A positive coefficient indicates that when the observation is in <strong>Fall</strong>, the predicted <strong>Aerosol_OD_Mean</strong> increases by about <strong>248.51</strong>.</li></ul><h3>7. Visualizing Model Performance</h3><p>So far, I’ve trained the model, made predictions and understand the importance of each feature. Now, we will create visualizations for <strong>feature importance</strong> and <strong>residuals</strong> to assess the model’s quality and interpretability.</p><p>Here’s the code to plot feature importance:</p><pre>@task<br>def plot_feature_importance(model):<br>    &quot;&quot;&quot;<br>    Plots the feature importances (coefficients) from the model.<br>    <br>    Parameters:<br>    - model: The trained model<br>    <br>    Displays:<br>    - A horizontal bar plot of feature importances.<br>    &quot;&quot;&quot;<br>    # Extract coefficients from the model<br>    coefficients = model.named_steps[&quot;ridge&quot;].coef_<br>    features = model.named_steps[&quot;onehotencoder&quot;].get_feature_names_out()<br>    <br>    # Create a Series for feature importances<br>    feat_imp = pd.Series(coefficients, index=features)<br>    <br>    # Sort by absolute value to prioritize the most influential features<br>    feat_imp = feat_imp.reindex(feat_imp.abs().sort_values().index)<br>    <br>    # Plot the feature importances<br>    feat_imp.plot(kind=&quot;barh&quot;, figsize=(10, 6))<br>    plt.title(&quot;Feature Importance (Coefficients from Ridge Model)&quot;)<br>    plt.xlabel(&quot;Coefficient Value&quot;)<br>    plt.ylabel(&quot;Features&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bKzk2xtklESLRgW-7VZAyg.png" /><figcaption>Feature importance (Coefficients from Ridge Model)</figcaption></figure><h4>7.2. Plotting Residuals</h4><p>Residuals are the differences between the predicted and actual values of the target variable. Plotting the residuals will helps us understand how well the model is fitting the data and whether there are any systematic patterns in the errors.</p><p>We will use a <strong>histogram</strong> combined with a <strong>kernel density estimate (KDE)</strong> to visualize the residuals. The KDE shows the distribution of residuals, allowing us to see whether the errors are normally distributed or skewed.</p><p>Here’s the code to plot residuals:</p><pre>@task<br>def plot_residuals(y_test, y_test_pred):<br>    &quot;&quot;&quot;<br>    Plots the residuals distribution to visualize how well the model fits the data.<br>    <br>    Parameters:<br>    - y_test: Actual target values in the test set<br>    - y_test_pred: Predicted target values by the model<br>    <br>    Displays:<br>    - A histogram with a kernel density estimate (KDE) of residuals.<br>    &quot;&quot;&quot;<br>    # Calculate residuals<br>    residuals = y_test - y_test_pred<br>    <br>    # Plot the residuals distribution with a KDE (Kernel Density Estimate)<br>    sns.histplot(residuals, kde=True, bins=30, color=&#39;blue&#39;)<br>    plt.title(&quot;Residuals Distribution&quot;)<br>    plt.xlabel(&quot;Residuals&quot;)<br>    plt.ylabel(&quot;Frequency&quot;)<br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9CikhTSZQuGf3840" /><figcaption>Residuals Plot</figcaption></figure><h4>7.3. Interpreting the Results</h4><p>After running the visualizations, we can draw the following conclusions:</p><p>Baseline Metrics (Training Data):</p><ul><li>Aerosol_OD_Mean: -2231.91</li><li>Baseline MAE: 3665.69</li></ul><p>Test Metrics (Validation Data):</p><ul><li>Aerosol_test_OD_Mean: -2251.81</li><li>Test Baseline MAE: 3687.01</li></ul><p>Ridge Regression Results (Test Data):</p><ul><li>Test Model MAE: 3150.46</li></ul><p>The Ridge Regression model achieved a <strong>Mean Absolute Error (MAE) of 3150.46</strong>, which is a significant improvement compared to the <strong>Baseline MAE of 3687.01</strong>. This reduction (~536.55) shows that the Ridge model captured meaningful relationships between the input features and the target variable.</p><h4>Model formular:</h4><p><strong>y= −(0.8963×longitude) −(12.6797×season_Spring) +(58.2488×season_Winter) −(109.9788×latitude) +(248.5084×season_Fall) −(294.0775×season_Summer)</strong></p><h4>What the Formula Tells Us:</h4><p>The formula shows that <strong>latitude</strong> and <strong>longitude</strong> influence <strong>Aerosol_OD_Mean</strong>, but <strong>seasonal</strong> factors have even larger impacts.</p><ul><li><strong>Seasons</strong> (Spring, Summer, Fall, Winter) have a <strong>strong influence</strong> on the predicted value, with <strong>Fall</strong> and <strong>Winter</strong> increasing it, and <strong>Spring</strong> and <strong>Summer</strong> decreasing it.</li><li><strong>Latitude</strong> also plays a major role, with <strong>higher latitudes</strong> leading to lower <strong>Aerosol_OD_Mean</strong> values.</li><li><strong>Longitude</strong> has a smaller negative impact.</li></ul><h4>What the Feature Importance tells us:</h4><ul><li><strong>Longitude</strong>: Minor negative effect (-0.8963). AOD decreases slightly as longitude increases.</li><li><strong>Latitude</strong>: Strong negative effect (-109.98). AOD is significantly lower at higher latitudes, farther from the equator.</li><li><strong>Spring</strong>: Moderate negative effect (-12.68). AOD slightly decreases in this season.</li><li><strong>Winter</strong>: Moderate positive effect (58.25). AOD increases during Winter.</li><li><strong>Fall</strong>: Strongest positive effect (248.51). AOD is highest in Fall.</li><li><strong>Summer</strong>: Strongest negative effect (-294.08). AOD is lowest in Summer.</li></ul><p><strong>Conclusion</strong>: Seasonal variations dominate AOD predictions, with latitude also playing a significant role.</p><p><strong>What the Residuals Plot tells us</strong>:</p><p><em>covers face</em></p><p>The residuals’ distribution suggests <strong>my model is not fully correct</strong>. Here’s why:</p><ol><li><strong>The bimodal shape</strong> of the residuals means the model struggles to predict accurately for all data points. It performs well for some cases but poorly for others, indicating potential issues like unaccounted variables or nonlinearity.</li><li><strong>Wide range of errors</strong> (from -12,500 to +7,500) shows large prediction mistakes in some cases.</li></ol><h3>Verdict:</h3><p>The model has issues and needs improvement. It might not be capturing the relationships in the data properly, so adjustments or a more advanced model might be necessary.</p><p>To improve the model, I might need to consider nonlinear methods (e.g., polynomial regression, random forests, or gradient boosting) to capture complex relationships in the variables. For a more robust analysis, I will also need to get a more comprehensive dataset to account for several other variables.</p><h3>Conclusion</h3><p>This project showcases a comprehensive approach to analyzing aerosol data and developing predictive models for Aerosol Optical Depth (AOD). From data ingestion and cleaning to exploratory analysis, and predictive modeling, each step offered valuable insights into understanding the relationships between atmospheric variables and AOD.</p><h3>Key Takeaways</h3><ol><li><strong>Baseline Performance:</strong> Using the mean as a predictor highlighted the limitations of simplistic models, serving as a benchmark for improvement.</li><li><strong>Model Performance:</strong> The Ridge Regression model achieved a significant reduction in Mean Absolute Error (MAE) compared to the baseline. This demonstrates its ability to capture meaningful patterns in the data. However, its performance revealed limitations in addressing complex relationships, as evidenced by the residual analysis.</li><li><strong>Insights Gained:</strong> The AOD is influenced by Seasonal variations and latitude.</li><li><strong>Challenges Identified:</strong> The residuals analysis exposed potential shortcomings in the model.</li></ol><h3>Future Directions</h3><p>While the Ridge Regression model offered valuable insights, the complexity of atmospheric systems shows the need for more advanced approaches, such as nonlinear modeling techniques. Also, additional features like humidity or wind speed will inform dataset enrichment, and help uncover overlooked factors and refine predictions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f9ab1a463a8" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/a-predictive-model-for-aerosol-data-analysis-8f9ab1a463a8">A Predictive Linear Model for Aerosol Data Analysis</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[Scalable Data Workflow with Prefect, Kafka, and Terraform]]></title>
            <link>https://blog.devgenius.io/scalable-data-workflow-with-prefect-kafka-and-terraform-1841af054f61?source=rss-4e93c4cff640------2</link>
            <guid isPermaLink="false">https://medium.com/p/1841af054f61</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[prefect]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Fagbuyi Temitope Emmanuel]]></dc:creator>
            <pubDate>Fri, 13 Dec 2024 02:43:47 GMT</pubDate>
            <atom:updated>2024-12-31T17:57:21.523Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>Modern data systems demand scalability, flexibility, and robustness, especially in the era of big data and real-time analytics. In this article, I share how I built a seamless pipeline to fetch financial data, stream it using Kafka, orchestrate the workflow with Prefect, and store the processed data in Google Cloud Storage (GCS). By automating infrastructure provisioning with Terraform, I created a scalable and production-ready pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LsQzDjAGe9e5Ah-K17cMmA.png" /><figcaption>Pipeline Architecture</figcaption></figure><p>Through this hands-on guide, you’ll learn how I:<br>- Use Prefect for orchestrating data workflows.<br>- Leverage Kafka for real-time data streaming.<br>- Automate cloud infrastructure provisioning with Terraform.<br>- Upload processed data to Google Cloud Storage using Python.</p><p>Here is the full code: <a href="https://github.com/Tofag-py/marketstackdatapipeline.git"><strong>MarketStackDataPipeline</strong></a></p><p><strong>1. Prefect Pipelines for Data Ingestion and Transformation</strong></p><p><strong>Problem:</strong> The first challenge was orchestrating the fetching, processing, and merging of financial data from APIs into a reusable pipeline. Previously, my workflows were ad hoc and relied on custom scripts that were difficult to maintain and prone to failure. Prefect provided a clean, modular, and fault-tolerant framework to orchestrate these tasks.</p><p>The goal was simple: fetch financial market data via APIs, process it efficiently, and ensure it was ready for downstream consumers. Prefect allowed me to break the workflow into smaller, reusable tasks with built-in error handling and logging.</p><p>Key features of this solution included modularity, reusability, and resilience. Each task was designed to be independent, making it easier to debug, test, and maintain. Prefect’s error-handling capabilities provided peace of mind by ensuring tasks could retry or fail gracefully without disrupting the entire workflow.</p><p>Here’s how we set up the pipeline:</p><pre>from prefect import task, flow<br>import json<br>from ingestion import load_config, fetch_data, merge_data, load_existing_data<br>@task<br>def fetch_and_merge_data(api_key, url, existing_data_path):<br> &quot;&quot;&quot;Fetch new data from the API and merge it with existing data.&quot;&quot;&quot;<br> # Load existing data<br> existing_data = load_existing_data(existing_data_path)<br># Fetch new data<br> new_data = fetch_data(api_key, url)<br># Merge datasets<br> merged_data = merge_data(existing_data, new_data)<br> return merged_data<br>@flow<br>def main_pipeline():<br> &quot;&quot;&quot;Orchestrate the data pipeline.&quot;&quot;&quot;<br> # Load API configuration<br> api_config = load_config()<br> api_key = api_config.get(&#39;api_key&#39;)<br> url = (&quot;http://api.marketstack.com/v1/eod?access_key={api_key}&amp;symbols=AAPL&quot;<br> &quot;&amp;date_from=2020–01–01&amp;date_to=2024–12–31&amp;sort=DESC&quot;)<br># Fetch and process data<br> merged_data = fetch_and_merge_data(api_key, url, &#39;../data/output_data.json&#39;)<br> return merged_data<br>if __name__ == &quot;__main__&quot;:<br> main_pipeline()</pre><p>Key Features:<br><strong>Modular Tasks:</strong> Each function, like `fetch_data` or `merge_data`, is reusable and testable.<br><strong>Error Handling:</strong> Prefect’s built-in retry and failure notifications ensure resilience.</p><h3>2. Streaming Data with Kafka</h3><p>Once the data was processed, the next challenge was ensuring it could be accessed in real-time. Financial data is only valuable if it’s timely, and static storage wasn’t going to cut it.</p><p>Enter Kafka.</p><p>Kafka is a distributed event-streaming platform known for its reliability and scalability. It allowed us to stream data in real time, ensuring downstream consumers always have access to the latest updates.</p><p>Setting up Kafka wasn’t without its challenges. Configuring producers and consumers requires careful tuning to ensure optimal performance.</p><p>Here’s a simplified example of how I implemented a Kafka producer:</p><pre>from confluent_kafka import Producer<br>import json<br>@task<br>def create_producer(config):<br> producer = Producer(config)<br> return producer<br>@task<br>def produce_message(producer, topic, data):<br> &quot;&quot;&quot;Send data to a Kafka topic.&quot;&quot;&quot;<br> data_str = json.dumps(data) if not isinstance(data, str) else data<br> producer.produce(topic, value=data_str)<br> producer.flush()</pre><p><strong>Consumer Implementation:</strong></p><pre>from confluent_kafka import Consumer<br>@task<br>def create_consumer(config):<br> consumer = Consumer(config)<br> return consumer<br>@task<br>def consume_message(topic, config, timeout=10):<br> &quot;&quot;&quot;Consume messages from Kafka with a timeout.&quot;&quot;&quot;<br> config[&quot;group.id&quot;] = &quot;MarketStack1&quot;<br> config[&quot;auto.offset.reset&quot;] = &quot;earliest&quot;<br> consumer = Consumer(config)<br> consumer.subscribe([topic])<br>try:<br> while True:<br> msg = consumer.poll(timeout)<br> if msg is None:<br> print(&quot;No more messages or timeout reached. Exiting…&quot;)<br> break<br> if msg.error() is None:<br> print(f&quot;Consumed message: {msg.key()} - {msg.value()}&quot;)<br> finally:<br> consumer.close()</pre><p><strong>Key Features:</strong></p><p><strong>Data Serialization: </strong>Data is serialized into JSON format for consistent processing.<br><strong>Scalability:</strong> Kafka’s distributed nature ensures that producers and consumers can scale independently.</p><h3>3. Automating Infrastructure with Terraform</h3><p>Building a data pipeline isn’t just about code but also infrastructure. Without a solid foundation, even the best pipeline will crumble. But provisioning resources manually wasn’t sustainable.</p><p>Enter Terraform. By using Infrastructure as Code (IaC), I automated the creation of the cloud resources, from storage buckets to compute instances. This not only reduced errors but also ensured consistency across environments.</p><p>Here’s an excerpt from our Terraform configuration:</p><pre>provider &quot;google&quot; {<br>  credentials = file(&quot;../ConfigFiles/marketstack_ingress.json&quot;)<br>  project     = &quot;data-streaming-project-433810&quot;<br>  region      = &quot;us-central1&quot;<br>}<br><br>resource &quot;google_storage_bucket&quot; &quot;marketstack_ingress_lake&quot; {<br>  name     = &quot;marketstack-data-lake&quot;<br>  location = &quot;US&quot;<br>}<br><br>resource &quot;google_compute_instance&quot; &quot;marketstack_ingress_instance&quot; {<br>  name         = &quot;ingress-instance&quot;<br>  machine_type = &quot;e2-micro&quot;<br>  zone         = &quot;us-central1-a&quot;<br>  boot_disk {<br>    initialize_params {<br>      image = &quot;ubuntu-os-cloud/ubuntu-2204-lts&quot;<br>    }<br>  }<br>}</pre><h3>4. Uploading Data to Google Cloud Storage</h3><p>The final step in our workflow was storing the processed data. For this, I chose Google Cloud Storage (GCS), a reliable and scalable option for centralizing data.</p><p>GCS allowed us to store processed financial data securely, ensuring it was accessible for downstream analytics or archival purposes. Integrating GCS with our pipeline was straightforward using Python’s google.cloud.storage library.</p><p>This is an excerpt of the code:</p><pre>from google.cloud import storage<br><br>def upload_to_gcs(bucket_name, file_path, destination_blob_name):<br>    &quot;&quot;&quot;<br>    Upload a file to GCS.<br>    &quot;&quot;&quot;<br>    client = storage.Client()<br>    bucket = client.bucket(bucket_name)<br>    blob = bucket.blob(destination_blob_name)<br>    blob.upload_from_filename(file_path)<br>    print(f&quot;File {file_path} uploaded to {bucket_name}/{destination_blob_name}.&quot;)</pre><h3>5. <strong>Automating Script Execution with a Bash Script</strong></h3><p>To streamline the execution of the data ingestion pipeline, I created a bash script to automate the process. This script ensures that the correct environment is activated and the pipeline runs without manual intervention. It’s particularly useful for scheduling jobs using cron or other task schedulers.</p><p>The bash script performs the following tasks:</p><ol><li>Navigates to the directory containing the Python script.</li><li>Sources the Anaconda setup to enable environment management.</li><li>Activates the specific conda environment required for the project.</li><li>Executes the Python script to initiate the data ingestion pipeline.</li></ol><p>Here’s the bash script I used:</p><pre>#!/bin/bash<br><br># Navigate to the directory containing your Python script<br>cd DataIngestion/ingestion.py<br><br># Source conda setup script<br>source /Users/tofag/anaconda3/etc/profile.d/conda.sh<br><br># Activate conda environment<br>conda activate Tofag3.10<br><br># Run the Python script<br>python ingestion.py</pre><p>This script adds an additional layer of automation, reducing the risk of human error during execution. By integrating it into the workflow, I was able to focus on pipeline optimization and analytics instead of repetitive tasks.</p><h3>5. <strong>Results and Observations</strong>:</h3><ul><li><strong>Prefect Workflow:</strong> Simplified the data ingestion and processing by introducing modularity and fault tolerance.</li><li><strong>Kafka Streaming:</strong> Ensured real-time data availability, improving decision-making by providing timely updates.</li><li><strong>Terraform Provisioning:</strong> Automated infrastructure setup, saving time and reducing the risk of human error.</li><li><strong>GCS Storage:</strong> Offered a scalable solution for centralizing data, enabling seamless downstream access and analysis.</li></ul><p>This combination of tools resulted in a system that was not only scalable but also operationally efficient.</p><h3>6. Challenges and Lessons Learned</h3><p>No project is without challenges, and this one provided valuable learning opportunities:</p><ul><li><strong>API Rate Limits:</strong> The free tier for the data provider imposed strict limits, requiring careful planning to avoid exhausting the allowance during development.</li><li><strong>Kafka Timeouts:</strong> Initial issues with consumer timeouts highlighted the need for fine-tuning polling intervals, improving reliability, and reducing latency.</li><li><strong>Terraform Debugging:</strong> Resource dependencies were challenging during the initial deployments but became manageable with iterative refinement.</li></ul><p>Each of these hurdles underscored the importance of planning, testing, and refining throughout the development process.</p><h3><strong>7. Future Enhancements</strong></h3><p>While the pipeline is operational, I see opportunities for improvement:</p><ul><li><strong>Integrating BigQuery:</strong> Adding advanced analytics capabilities by integrating with Google BigQuery for faster and more comprehensive insights.</li><li><strong>Monitoring and Alerts:</strong> Setting up Prometheus and Grafana for real-time monitoring of system performance, allowing for proactive issue resolution.</li><li><strong>Scaling Consumers:</strong> Implementing multiple Kafka consumer groups to enhance throughput and improve the pipeline’s ability to handle larger data volumes.</li><li><strong>Data Analysis:</strong> Performing deeper analysis using tools like Pandas, Plotly, and Matplotlib.</li></ul><p><strong>Conclusion</strong><br>By integrating Prefect, Kafka, Terraform, GCS, and a bash script, I built a scalable, automated, and cloud-native data pipeline. The bash script streamlined the pipeline’s execution by automating the setup and activation of the required environment, adding an extra layer of efficiency to the workflow. This end-to-end system ensures real-time data processing, robust infrastructure, and seamless storage, providing a foundation for advanced analytics and growth.</p><p>Whether you’re a data engineer or a cloud enthusiast, this project highlights how combining modern tools and thoughtful automation can address complex data workflow challenges effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1841af054f61" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/scalable-data-workflow-with-prefect-kafka-and-terraform-1841af054f61">Scalable Data Workflow with Prefect, Kafka, and Terraform</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[Building a Robust Data Pipeline with Docker, PostgreSQL, and Python]]></title>
            <link>https://medium.com/@tofag/building-a-robust-data-pipeline-with-docker-postgresql-and-python-1fc01e76b09a?source=rss-4e93c4cff640------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fc01e76b09a</guid>
            <category><![CDATA[dezoomcamp]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <dc:creator><![CDATA[Fagbuyi Temitope Emmanuel]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 14:17:49 GMT</pubDate>
            <atom:updated>2024-01-30T14:17:49.534Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this project, we embark on the journey of constructing a robust data pipeline designed for data retrieval, processing, and storage. The primary goal is to create a system that automates the daily update of a local dataset using a combination of Python, Docker, PostgreSQL, Pgcli, PgAdmin, and related tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/0*YuwZirShEQtxJxWB.png" /></figure><h3>First File: Main.py</h3><p>Our first file, main.py, initiates the data pipeline by extracting information from a public API. Let&#39;s break down the key components of this script:</p><h4>Importing Libraries</h4><p>We begin by importing essential libraries. Pandas is employed for data manipulation, requests for handling HTTP requests, and json for working with JSON data.</p><pre>import pandas as pd<br>import requests<br>import json</pre><h4>Function to Get Data from URL</h4><p>The get_data function performs an HTTP GET request to a specified URL, converting the obtained data to JSON format. It gracefully handles HTTP errors and general request exceptions.</p><pre>def get_data(url: str):<br>    try:<br>        raw_data = requests.get(url)<br>        raw_data.raise_for_status() <br>        data = raw_data.json()<br>        return data<br>    except requests.exceptions.HTTPError as errh:<br>        print(f&quot;HTTP Error: {errh}&quot;)<br>    except requests.exceptions.RequestException as err:<br>        print(f&quot;Request Error: {err}&quot;)<br>    return None</pre><h4>Function to Download Data Locally</h4><p>The download_local function attempts to save the obtained JSON data to a local file, with error handling for IO issues.</p><pre>def download_local(data: dict, local_path: str):<br>    try:<br>        with open(local_path, &#39;w&#39;, encoding=&#39;utf-8&#39;) as file:<br>            json.dump(data, file, ensure_ascii=False, indent=4)<br>        print(f&quot;Data downloaded and saved to {local_path}&quot;)<br>        return data<br>    except IOError as e:<br>        print(f&quot;Error writing to file: {e}&quot;)<br>    return None</pre><h4>Function to Download and Extract Fields</h4><p>The download_and_extract_fields function extracts specific fields from the data, creates a Pandas DataFrame, and saves it as a CSV file.</p><pre>def download_and_extract_fields(data: dict, local_path: str):<br>    try:<br>        extracted_data = []<br>        for entry in data:<br>            extracted_entry = {<br>                # List of extracted fields...<br>            }<br>            extracted_data.append(extracted_entry)<br>        df = pd.DataFrame(extracted_data)<br>        df.to_csv(local_path, index=False)<br>        print(f&quot;Data extracted and saved to {local_path}&quot;)<br>        return df<br>    except IOError as e:<br>        print(f&quot;Error writing to file: {e}&quot;)<br>    return None</pre><h4>Main Execution Block</h4><p>In the main block, we specify the URL for data retrieval, attempt to get data, and if successful, download it locally and extract relevant fields.</p><pre>if __name__ == &quot;__main__&quot;:<br>    url = &quot;https://data.cityofchicago.org/resource/ijzp-q8t2.json?&quot;<br>    data = get_data(url)<br>    if data:<br>        local_path = &quot;/Users/tofag/Desktop/ReadWrite Assignments/FBI_data/extracted_chicago_crime_data.csv&quot;  <br>        download_local(data, local_path)<br>        download_and_extract_fields(data, local_path)<br>    else:<br>        print(&quot;Data retrieval failed.&quot;)</pre><h3>Second File: Pipeline.py</h3><p>The second file, pipeline.py, focuses on creating a pipeline that pushes the local file to a PostgreSQL database. Let&#39;s explore its components:</p><h4>Importing Libraries</h4><p>We import necessary libraries, including Pandas for data manipulation, create_engine from sqlalchemy for database connection, and argparse for parsing command-line arguments.</p><pre>import pandas as pd<br>from sqlalchemy import create_engine<br>import argparse</pre><h4>Function to Parse Command-line Arguments</h4><p>The parse_arguments function sets up an argument parser, defining parameters for connecting to a PostgreSQL database.</p><pre>def parse_arguments():<br>    parser = argparse.ArgumentParser(description=&#39;Ingest CSV data to Postgres&#39;)<br>    parser.add_argument(&#39;--user&#39;, help=&#39;user name for postgres&#39;, required=True)<br>    # ... (other arguments)<br>    return parser.parse_args()</pre><h4>Function to Make Database Connection</h4><p>The make_connection function establishes a connection to the PostgreSQL database using the provided connection string.</p><pre>def make_connection(conn: str):<br>    return create_engine(conn).connect()</pre><h4>Function to Read Data from CSV</h4><p>The read_data_from_csv function attempts to read data from a CSV file, returning a DataFrame if successful.</p><pre>def read_data_from_csv(file_path: str):<br>    try:<br>        df = pd.read_csv(file_path)<br>        return df<br>    except Exception as e:<br>        print(f&quot;Error reading data from CSV: {e}&quot;)<br>        return None</pre><h4>Function to Manipulate Data</h4><p>The manipulate_data function takes a DataFrame as input and performs manipulations, such as converting date columns to datetime and casting certain columns to boolean types.</p><pre>def manipulate_data(df: pd.DataFrame):<br>    df[&#39;date&#39;] = pd.to_datetime(df[&#39;date&#39;])<br>    df[&#39;arrest&#39;] = df[&#39;arrest&#39;].astype(bool)<br>    df[&#39;domestic&#39;] = df[&#39;domestic&#39;].astype(bool)<br>    return df</pre><h4>Function to Push Data to Database</h4><p>The push_to_db function pushes data to the PostgreSQL database in chunks, handling success or failure for each chunk.</p><pre>def push_to_db(df: pd.DataFrame, engine, table_name: str):<br>    chunk_size = 10000<br>    num_chunks = len(df) // chunk_size + 1<br>    for i in range(num_chunks):<br>        start_idx = i * chunk_size<br>        end_idx = (i + 1) * chunk_size<br>        chunk = df.iloc[start_idx:end_idx]<br>        try:<br>            chunk.head(n=0).to_sql(name=table_name, con=engine, if_exists=&#39;replace&#39;)<br>            chunk.to_sql(name=table_name, con=engine, if_exists=&#39;append&#39;, index=False)<br>            print(f&quot;Data successfully pushed to the database for chunk {i + 1}/{num_chunks}.&quot;)<br>        except Exception as e:<br>            print(f&quot;Error pushing data to the database: {e}&quot;)</pre><h4>Main Execution Block</h4><p>In the main block, we parse command-line arguments, construct the connection string, initiate the database connection, read data from a CSV file, manipulate it, and push it to the database.</p><pre>if __name__ == &quot;__main__&quot;:<br>    args = parse_arguments()<br>    connection_string = f&#39;postgresql://{args.user}:{args.password}@{args.host}:{args.port}/{args.db}&#39;<br>    table_name = args.table_name<br>    engine = make_connection(connection_string)<br>    if engine:<br>        data_path = &#39;FBI_data/extracted_chicago_crime_data.csv&#39;<br>        data_frame = read_data_from_csv(data_path)<br>        if data_frame is not None:<br>            manipulated_data = manipulate_data(data_frame)<br>            push_to_db(manipulated_data, engine, table_name)<br>            print(&quot;Data pushed successfully&quot;)<br>        else:<br>            print(&quot;Failed to read data from CSV.&quot;)<br>    else:<br>        print(&quot;Failed to establish a database connection.&quot;)</pre><h3>Docker Container Setup</h3><p>For the sake of this project, we utilize two Docker containers — one for the PostgreSQL database and another for the PgAdmin GUI. A Docker network is created to facilitate communication between the two containers.</p><h4>PostgreSQL Container</h4><p>We run a PostgreSQL container, specifying environment variables for the PostgreSQL username, password, and database name. A volume is mounted to link the local directory with the container’s PostgreSQL data directory.</p><pre>docker run -it \<br>    -e POSTGRES_USER=root \<br>    -e POSTGRES_PASSWORD=root \<br>    -e POSTGRES_DB=chicago_crime_data \<br>    -v &quot;$(pwd)/chicago_crime_data:/var/lib/postgresql/data&quot; \<br>    -p 5432:5432 \<br>    --name chicago_crime_data_database \<br>    --network=chicago_crime_network \<br>    postgres:13</pre><h4>pgcli (PostgreSQL Client)</h4><p>We connect to the PostgreSQL database using pgcli, specifying the host, port, username, and database.</p><pre>pgcli -h localhost -p 5432 -U root -W chicago_crime_data</pre><h4>pgAdmin Container</h4><p>A pgAdmin container is run, setting environment variables for the default email and password.</p><pre>docker run -it \<br>    -e PGADMIN_DEFAULT_EMAIL=&quot;admin@admin.com&quot; \<br>    -e PGADMIN_DEFAULT_PASSWORD=&quot;root&quot; \<br>    -p 8080:80 \<br>    --network=chicago_crime_network \<br>    --name pgadmin \<br>    dpage/pgadmin4</pre><h4>Docker Network Creation</h4><p>We create a Docker network named chicago_crime_network.</p><pre>docker network create chicago_crime_network</pre><h3>Python Script Execution</h3><h4>Running pipeline.py Python Script</h4><p>We execute the pipeline.py script, passing various command-line arguments such as PostgreSQL credentials and table information.</p><pre>python pipeline.py \<br>    --user=root \<br>    --password=root \<br>    --host=localhost \<br>    --port=5432 \<br>    --db=chicago_crime_data \<br>    --table_name=chicago_crime_data</pre><h3>Third File: Dockerfile</h3><p>In the Dockerfile, we define the specifications for building a Docker image to run the pipeline.</p><h4>Base Image and Working Directory</h4><p>We use an official Python runtime as the parent image for the Docker container (specifically Python version 3.10). The working directory within the container is set to /app.</p><pre># Use an official Python runtime as a parent image<br>FROM python:3.10<br># Set the docker working directory to /app<br>WORKDIR /app</pre><h4>Copying Files into the Container</h4><p>We copy the contents of the current directory into the container at the specified path, /app.</p><pre># Copy the current directory contents into the container at /app<br>COPY . /app</pre><h4>Installing Packages</h4><p>We update the package list and install necessary packages within the container, including the wget tool and Python packages (pandas, requests, psycopg2, sqlalchemy, requests).</p><pre># Install any needed packages<br>RUN apt-get update &amp;&amp; apt-get install -y wget<br>RUN pip install pandas requests psycopg2 sqlalchemy requests</pre><h4>Running the Python Scripts</h4><p>We specify that the main.py script should be run when the container is started.</p><pre># Run the main.py script<br>CMD [&quot;python&quot;, &quot;main.py&quot;]</pre><h4>Making pipeline.py Executable and Setting as an Entrypoint</h4><p>We set pipeline.py as an executable and specify it as the entry point for the Docker container.</p><pre># Make pipeline.py executable and provide as an entrypoint<br>ENTRYPOINT [&quot;python&quot;, &quot;pipeline.py&quot;]</pre><h4>Docker Image Build and Run</h4><h4>Docker Image Build</h4><p>We build the Docker image and give it the name crime_data.</p><pre>docker build -t crime_data .</pre><h4>Docker Container Run</h4><p>We run a Docker container based on the crime_data image, passing command-line arguments to the container, and specifying PostgreSQL credentials and table information.</p><pre>docker run crime_data:v01 \<br>    --user=root \<br>    --password=root \<br>    --host=localhost \<br>    --port=5432 \<br>    --db=chicago_crime_data \<br>    --table_name=chicago_crime_data</pre><p>With the postgres and pgadmin containers running, we ran the crime_data image.</p><p>On login into the pgadmin localhost page and connecting to the [ostgresql server, here is the state of the database from the GUI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oW7HDcRKYw_0rM3BUiOU0g.png" /></figure><h3>Conclusion</h3><p>This project successfully demonstrates the creation of a robust data pipeline for automating the daily update of a local dataset. By combining the power of Python for data manipulation with the containerization benefits offered by Docker, we’ve created a scalable and efficient system for handling data workflows. The inclusion of PostgreSQL for database management and PgAdmin for a user-friendly GUI enhances the overall functionality and manageability of the data pipeline. This solution provides a comprehensive framework that can be easily deployed and adapted for similar data automation tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fc01e76b09a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced-Data Modeling Techniques for Efficient Analytics (I)]]></title>
            <link>https://medium.com/@tofag/advanced-data-modeling-techniques-for-efficient-analytics-i-2013b23c1508?source=rss-4e93c4cff640------2</link>
            <guid isPermaLink="false">https://medium.com/p/2013b23c1508</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-modelling]]></category>
            <dc:creator><![CDATA[Fagbuyi Temitope Emmanuel]]></dc:creator>
            <pubDate>Thu, 25 May 2023 18:42:09 GMT</pubDate>
            <atom:updated>2023-05-25T18:42:09.022Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*W7s6FtYWefBJ-WWG.png" /></figure><p>Data modeling is a critical aspect of data engineering as without it, it would be almost impossible to make actual sense of the data for analytics and reporting. Data modeling involves structuring and organizing data to support efficient data analysis and retrieval.</p><blockquote>Data modeling is the process of analyzing and defining all the different data your business collects and produces, as well as the relationships between those bits of data. (<a href="https://powerbi.microsoft.com/en-us/what-is-data-modeling/">Microsoft</a>)</blockquote><p>In this article, I will explore advanced data modeling techniques that empower data engineers to design robust and optimized data models for analytics purposes. By leveraging these techniques, you can enhance your organization’s data-driven decision-making capabilities and extract valuable insights from their data.</p><h3>Table of Contents:</h3><p>(I) <em>Understanding the Fundamentals of Data Modeling:</em></p><ul><li><em>Overview of data modeling concepts (entities, attributes, relationships)</em></li><li><em>Importance of conceptual, logical, and physical data models</em></li><li><em>Key considerations for designing data models for analytics</em></li></ul><h3>Understanding the Fundamentals of Data Modeling:</h3><h4>Overview of data modeling concepts (entities, attributes, relationships)</h4><p>Data models define the structure, relationships, and constraints of the data within a system or database. They provide a conceptual blueprint that helps you understand how data is organized and related to each other. Data models capture the entities (objects or concepts) and their attributes, as well as the relationships between entities.</p><p><strong>Entities</strong>: are distinct objects, concepts, or things in the business data structure or the real world. For example, for an Inventory Management System, the entities can include products, products, suppliers, warehouses, etc. In some climes, Entities are also called Key Figures (KF).</p><p><strong>Attributes</strong>: are properties or characteristics of these entities. They define, qualify and give key details of the Entities. For our IMS, the attributes of the entities can include item codes, quantities, and prices.</p><p><strong>Relationships</strong>: define the connection between Entities. The relationship is popularly depicted in an E-R diagram. The relationship between Entities can be one-to-one, one-to-many, or many-to-many, depending on the complexity of the association.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*tiVc0OFrstTMdbt2qiZz5g.png" /><figcaption>An example of an E/R diagram (Source: An Introduction to Database Systems, 8th Edition)</figcaption></figure><h3>Importance of conceptual, logical, and physical data models</h3><p>Designing a data model happens in stages. They are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/0*6gznir-AqNREJKAw" /></figure><ul><li><strong>Conceptual data models</strong>: This type of model provides a high-level overview of the entities, attributes, and relationships between them without going into the details. Hence, conceptual data models hardly have attributes, what you see are the entities and the relationships between them, not the details.</li></ul><blockquote>A <em>conceptual data model</em> is a model of the things in the business and the relationships among them, rather than a model of the data about those things. So in a conceptual data model, when you see an entity type called car, then you should think about pieces of metal with engines, not records in databases. (<a href="https://www.sciencedirect.com/topics/computer-science/conceptual-data-model#:~:text=A%20conceptual%20data%20model%20is%20a%20model%20of%20the%20things,engines%2C%20not%20records%20in%20databases.">Sciencedirect</a>)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*HsJhOK9GQUm-6TnU.png" /><figcaption>Conceptual Data Model (Source: Vertabelo)</figcaption></figure><ul><li><strong>Logical Data Model</strong>: This establishes a more detailed structure to the conceptual model by defining data elements, their relationships, and the rules that govern them. The Logical model is focused on the business requirement and this ensures that the model satisfies the business needs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yrmdgqyCMjZzK3sM.png" /></figure><ul><li><strong>Physical Data Model</strong>: The physical data model specifies the implementation details of the logical model. It highlights the relationships between the data objects. It defines how data will be stored, organized, and accessed in a specific DBMS or technology.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/0*eY_FscUPMI6ljLWq.png" /></figure><blockquote>A physical data model is a database-specific model that represents relational data objects (for example, tables, columns, primary and foreign keys) and their relationships. A physical data model can be used to generate DDL statements which can then be deployed to a database server. (<a href="https://www.ibm.com/docs/en/ida/9.1.1?topic=modeling-physical-data-models">IBM</a>)</blockquote><h3>Key considerations for designing data models for analytics</h3><p>As a data engineer, what are the things to consider while designing a data model?</p><ul><li>Business Requirements: Each model has a use case and answers to a specific purpose. Understanding the business goals, objectives, and specific analytics requirements is crucial in determining what the data model should support.</li><li>Data Analysis Needs: Once you have defined what the stakeholders require, you need to identify the types of analysis and queries that will be performed on the data. This includes considering the required granularity, dimensions, and metrics.</li><li>Data Integrity and Accuracy: It is also important to ensure that the data model maintains data integrity. Do this by enforcing constraints, validations, and business rules. Data accuracy and consistency are crucial for reliable analytics.</li><li>Scalability and Performance: Your data model should be scalable and capable to accommodate the expected data volume to support efficient data retrieval and analysis. You can consider indexing strategies, partitioning, and optimization techniques to improve the performance of your models.</li><li>Data Governance and Security: It goes without saying that data security and governance is important. Incorporate data governance principles to ensure data quality, security, and compliance. Define access controls, privacy measures, and data retention policies.</li></ul><p>In conclusion, data modeling is a fundamental and indispensable practice in data engineering for efficient analytics and reporting. By structuring and organizing data through the use of conceptual, logical, and physical data models, organizations can gain a comprehensive understanding of their data and its relationships. This understanding enables effective data analysis, reliable reporting, and data-driven decision-making.</p><p>Conceptual data models provide a high-level overview of entities and relationships, focusing on business concepts rather than data details. Logical data models add more granularity by defining data elements and their relationships, ensuring alignment with business requirements. Physical data models specify implementation details, including how data is stored, organized, and accessed in specific database management systems or technologies.</p><p>When designing data models for analytics, several key considerations come into play. Understanding the business requirements and specific analytics needs is essential to tailor the data model to the intended use case. Maintaining data integrity, accuracy, and consistency through constraints, validations, and business rules ensures reliable analytics results. Scalability and performance considerations involve designing models capable of handling expected data volumes efficiently, utilizing indexing strategies, partitioning, and optimization techniques. Incorporating data governance and security measures guarantees data quality, privacy, compliance, and access control.</p><p>By embracing advanced data modeling techniques and adhering to these considerations, data engineers can unlock the full potential of their organization’s data assets. With well-designed data models, businesses can uncover valuable insights, make informed decisions, and drive innovation and success in today’s data-driven world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2013b23c1508" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Ingestion with Prefect I]]></title>
            <link>https://medium.com/@tofag/data-ingestion-with-prefect-i-74d061e78e37?source=rss-4e93c4cff640------2</link>
            <guid isPermaLink="false">https://medium.com/p/74d061e78e37</guid>
            <category><![CDATA[prefect]]></category>
            <category><![CDATA[data-ingestion]]></category>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[dezoomcamp]]></category>
            <dc:creator><![CDATA[Fagbuyi Temitope Emmanuel]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 19:58:40 GMT</pubDate>
            <atom:updated>2023-03-31T19:58:40.949Z</atom:updated>
            <content:encoded><![CDATA[<h3>My Data Ingestion with Prefect I</h3><p><em>Aside: This series on Data Engineering will be quite personal and will be a walkthrough of my journey with the </em><a href="https://github.com/DataTalksClub/data-engineering-zoomcamp"><em>#dezoomcamp data engineering</em></a><em> training. NB: Kindly leave your comments and corrections if you find this educating or misleading, I won’t hesitate to make amendment(s).</em></p><p><em>This article is part of my project in the #dezoomcamp completion requirement. In this part 1, my python code will download my raw data from the URL, extract it and append it to a mega file before storing the file locally.</em></p><p>As data becomes increasingly important for businesses and organizations, the process of data ingestion has become more crucial. Data ingestion is the process of obtaining, importing, and processing data from various sources into a system or database. Data ingestion is an essential component of data analytics and is often the first step in data processing.</p><p>In this article, I will be exploring the data ingestion process using some Python libraries and Prefect.</p><p><a href="https://medium.com/@tofag/getting-started-with-prefect-dej-part7-40aa2a50a5f3">Prefect </a>is a powerful library that allows you to build, schedule, and monitor data pipelines. It provides a clean and intuitive API for creating and running workflows, making it an excellent choice for data ingestion tasks. The library is easy to use and allows you to build complex pipelines without much effort.</p><p>Here, I will be exploring how to use Prefect to download and process CSV files from a web server. I selected the COVID-19 dataset. The dataset contains daily reports of COVID-19 cases and deaths worldwide.</p><h3>Setting Up the Environment</h3><p>Before we get started, you will need to install the Prefect library. You can install the library using pip:</p><pre>pip install prefect</pre><p>We will also need to install the requests and pandas libraries, which we will use to download and manipulate the CSV files.</p><pre>pip install requests pandas</pre><h3>Creating a Prefect Flow</h3><p>Now that we have our environment set up, let’s create a Prefect flow.</p><p>A flow is a sequence of tasks that are executed in a specific order. In my case, I will create a flow that will download CSV files from a web server, save them to a local directory, and append them to a mega file.</p><p>Below is my full code:</p><pre>import os<br>import requests<br>from prefect import task, flow<br>import datetime<br>import pandas as pd<br><br># Create the data directory if it does not exist<br>@task(log_prints=True)<br>def make_path(data_dir):<br>    if not os.path.exists(data_dir):<br>        os.makedirs(data_dir)<br><br># Download csv from web<br>@task(log_prints=True)<br>def get_csv(date, base_url):<br>    &quot;&quot;&quot;Downloads the CSV file for the given date.&quot;&quot;&quot;<br>    url = base_url + date.strftime(&quot;%m-%d-%Y&quot;) + &quot;.csv&quot;<br>    response = requests.get(url)<br>    try:<br>        response.raise_for_status()<br>    except requests.exceptions.HTTPError as e:<br>        print(f&quot;HTTP error occurred while downloading data for {date}: {e}&quot;)<br>        return None<br>    return response.content<br><br>@task(log_prints=True)<br>def save_csv(data, date, data_dir):<br>    &quot;&quot;&quot;Saves the CSV data to a file with the given date.&quot;&quot;&quot;<br>    filename = os.path.join(data_dir, date.strftime(&quot;%m-%d-%Y&quot;) + &quot;.csv&quot;)<br>    with open(filename, &quot;wb&quot;) as f:<br>        f.write(data)<br><br># Append the csv files to a mega file<br>@task(log_prints=True)<br>def append_csv_to_mega_file(csv_data, date, data_dir) -&gt; str:<br>    &quot;&quot;&quot;Appends the CSV data to a mega file and stores it locally.&quot;&quot;&quot;<br>    mega_filename = &quot;mega_csv_file.csv&quot;<br>    mega_filepath = os.path.join(data_dir, mega_filename)<br>    csv_filename = date.strftime(&quot;%m-%d-%Y&quot;) + &quot;.csv&quot;<br>    csv_filepath = os.path.join(data_dir, csv_filename)<br><br>    # Append the CSV data to the mega file<br>    with open(mega_filepath, &quot;a&quot;) as mega_file:<br>        mega_file.write(csv_data.decode(&quot;utf-8&quot;))<br><br>    # Delete the CSV file after it has been appended to the mega file<br>    os.remove(csv_filepath)<br>    return mega_filepath<br><br>@task(log_prints=True)<br>def mega_file_path(mega_file):<br>    return mega_file<br><br><br>#Run the tasks<br>@flow(log_prints=True)<br>def web_to_local_flow():<br>    # Define the dates for which to download the CSV files<br>    start_date = datetime.date(2020, 1, 22)<br>    end_date = datetime.date.today()<br>    dates = [start_date + datetime.timedelta(days=x) for x in range((end_date - start_date).days + 1)]<br><br>    # Define the base URL for the CSV files<br>    base_url = &quot;https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/&quot;<br><br>    # Define the directory to store the downloaded CSV files<br>    data_dir = &quot;Ingest_files/covid_data&quot;<br><br>    # Define the Prefect flow<br>    make_path(data_dir)<br>    csv_data = get_csv.map(dates, base_url)<br>    csv_files = save_csv.map(csv_data, dates, data_dir)<br>    mega_file = append_csv_to_mega_file.map(csv_data, dates, data_dir)<br>    file_path = mega_file_path(mega_file)<br>    return file_path<br><br># Run the flow<br>if __name__ == &quot;__main__&quot;:<br>    web_to_local_flow()<br><br></pre><p>This script above defines a Prefect flow that downloads COVID-19 data in CSV format from the <a href="https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/">GitHub repository</a>, stores the files locally, and appends them to a mega file. The mega file is the final output of the flow, and its path is returned by the mega_file_path task.</p><p>The script defines four tasks:</p><ol><li>make_path: creates the data directory if it does not exist.</li><li>get_csv: downloads the CSV file for a given date from a URL.</li><li>save_csv: saves the CSV data to a file with the given date.</li><li>append_csv_to_mega_file: appends the CSV data to a mega file and deletes the original CSV file.</li></ol><p>The tasks are then chained together in the web_to_local_flow flow using the map method to apply the tasks to a list of dates. The final output of the flow is the path to the mega file, which is returned by the mega_file_path task.</p><p>The make_path task checks if the data directory exists and creates it if it doesn’t. The get_csv task downloads the CSV file for a given date from the web server, while the save_csv task saves the CSV data to a file. The append_csv_to_mega_file task appends the CSV data to a mega file and deletes the original CSV file after appending.</p><p>I then created a Prefect flow web_to_local_flow that runs the tasks in the order specified. We defined the start and end dates, created the data directory, downloaded the CSV files, and appended them to a mega file.</p><h3>Conclusion</h3><p>In this article, I explored the data ingestion process using Prefect, a Python library for building, scheduling, and monitoring data pipelines. I created a flow that downloads and processes CSV files from a web server and saves them to a local directory.</p><p>By using Prefect, I was able to create a simple, yet powerful data ingestion pipeline that can be easily extended to include more complex data processing tasks.</p><p>For the sake of emphasis, Prefect is an excellent library for anyone looking to automate their data ingestion processes and you should explore it further.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74d061e78e37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Overview of Batch Processing]]></title>
            <link>https://blog.devgenius.io/an-overview-of-batch-processing-9cc2ceea3c25?source=rss-4e93c4cff640------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cc2ceea3c25</guid>
            <category><![CDATA[batch-processing]]></category>
            <category><![CDATA[dezoomcamp]]></category>
            <category><![CDATA[data-modelling]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Fagbuyi Temitope Emmanuel]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 07:07:19 GMT</pubDate>
            <atom:updated>2023-03-02T08:33:30.243Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Batch Processing</h3><blockquote>Batch Processing: If you are working with large files, consider batch processing them. This allows you to apply changes to multiple files at once. —<a href="https://twitter.com/AyyazEdits/status/1630024811681292289?s=20"> Ayyaz Khan</a></blockquote><p>Batch processing is simply the method by which a large volume of data is collected, processed, and analyzed at once. In other words, it entails the process by which computers perform high-volume and repetitive tasks in batches. In batch processing, data is collected over a period of time and stored in a batch. The batch is then processed and analyzed as a whole. This is in contrast to real-time processing, where data is processed as soon as it is received.</p><p>Batch processing can be automated and scheduled to run at specific times or intervals maybe weekly, daily, hourly, etc, or by using a <a href="https://medium.com/@tofag/cron-jobs-perfect-for-automation-52c4060b5f13">cron job</a>, thereby reducing the need for manual intervention and improving efficiency.</p><p>Batch processing is a key concept in data engineering</p><h3>What are Batch Jobs?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*RfhCh88LWpesRGe7MmygcA.png" /></figure><p>Data engineering entails several processes, depending on the data you are working on and the requirement of the job. A batch job is a bunch of processes that you require to complete the ETL process of your data and analysis.</p><p>Some of the other processes that can be included in your batch job:</p><ol><li>Data extraction: This process involves you pulling data from various sources, such as databases, log files, or sensor data, and collecting it into your data lake for processing.</li><li>Data cleaning: Raw data often contains errors or inconsistencies, such as missing values or incorrect formatting. The data cleaning process corrects these errors and ensures the data is accurate and consistent.</li><li>Data transformation: You might need to transform your data into a different format or structure to be useful for downstream analysis or reporting.</li><li>Data analysis: Once you have cleaned and transformed, analysis can be done to derive insights and patterns.</li><li>Reporting: The results of the analysis can be compiled into reports or visualizations to communicate the findings to stakeholders or interested parties.</li><li>Data storage: After processing, the data can be stored in a database or other data warehouse for future use.</li><li>Error handling: In case of errors, such as data format errors or network connectivity problems, error handling can be included in your batch jobs to identify and resolve these issues to ensure your job runs successfully.</li></ol><h3>Tools for Batch Processing</h3><p>Several technologies can be used for batch processing including:</p><ul><li>Apache Hadoop</li><li>Apache Spark</li><li>Apache Flink</li><li>AWS Batch</li><li>Apache NiFi</li><li>Google Cloud Dataflow</li></ul><h3>Batch Processing vs Data Streaming</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*hEXwgfavFIXb9cWF7woQ0w.png" /></figure><p>Deciding the right data processing option for an organization is not optimal, as there is no right answer. the right solution depends on the organization’s needs and the data type.</p><p>Batch processing and data streaming are two different methods for processing data, and each has its own advantages and disadvantages.</p><p>Batch processing involves processing a large amount of data all at once, in a single batch or job. This approach is well-suited for processing large volumes of data that do not require real-time processing.</p><p>Data streaming, on the other hand, involves processing data in real timeas it is generated. This approach is well-suited for processing data that requires immediate action, such as sensor data, financial transactions, or social media feeds.</p><p>Here are some key differences between batch processing and data streaming:</p><ol><li>Speed: Batch processing is typically slower than data streaming, as it involves processing large volumes of data all at once. Data streaming, on the other hand, processes data in real time, allowing for immediate action and response.</li><li>Data volume: Batch processing is well-suited for processing large volumes of data, while data streaming is better suited for processing smaller, more frequent data streams.</li><li>Complexity: Batch processing is typically less complex than data streaming, as it involves processing data in a single job or batch. Data streaming, on the other hand, requires more complex systems and tools to process data in real time.</li><li>Latency: Batch processing jobs can have high latency, as they process data in large batches. Data streaming, on the other hand, has low latency, as it processes data in real time.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cc2ceea3c25" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/an-overview-of-batch-processing-9cc2ceea3c25">An Overview of Batch Processing</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[Popular commands in DBT: DEJ10]]></title>
            <link>https://blog.devgenius.io/popular-commands-in-dbt-dej10-650606681aad?source=rss-4e93c4cff640------2</link>
            <guid isPermaLink="false">https://medium.com/p/650606681aad</guid>
            <category><![CDATA[dezoomcamp]]></category>
            <category><![CDATA[cloud-data-warehouse]]></category>
            <category><![CDATA[dbt-models]]></category>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Fagbuyi Temitope Emmanuel]]></dc:creator>
            <pubDate>Sat, 25 Feb 2023 20:42:22 GMT</pubDate>
            <atom:updated>2023-02-27T18:15:03.078Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*ke0rcJhewSUjE2u-flEdEA.png" /></figure><p>If you’ve been using DBT, I bet you are in love already. That’s a testament of how seamless DBT makes data modeling.</p><p>However, there are too many commands. Maybe not too many, and I will be talking about the commands you should know about when using DBT.</p><h3>dbt init:</h3><p>This is the command that initializes a new DBT project and creates a project directory structure with configuration files. Once you have created a new project, and connected it to your Data Warehouse, running this command is the required first stey before running other DBT commands.</p><h3>dbt compile:</h3><p>After writing your SQL and Jinja model code, this command compiles the SQL code in the project and creates the SQL files in the target directory. Also, it validates the code against the schema defined in the database.</p><h3>dbt run:</h3><p>You will use this command often. After developing your models, you might need to run then intermittently to ensure your lineage works as your code becomes complicated. This command executes ALL the SQL files in your project.</p><p>To specify a particular file, you will need to add the select parameter.</p><pre>dbt run --select &lt;model_name&gt;</pre><h3>dbt test:</h3><p>So far you have specified the tests folder in your project yml file (this is done by default), this command runs tests defined in the tests directory and validates the data quality of the data pipeline.</p><p>The tests include checking for null values, ensuring the data type of the columns, and validating the data against expected results. This is an advised command before building and deploying your model.</p><h3>dbt deps:</h3><p>This command is quite important too. In most cases, you need to run it before running your models. This command installs the required dependencies for the project defined in the packages.yml file.</p><h3>dbt seed:</h3><p>Seeds are a predefined set of data that is used to populate a table or view. Seeds are typically used to provide initial data for testing and development purposes or to create lookup tables that are used throughout the data model. In other cases, seeds are used to upload data that doesn’t change often.</p><p>This command loads the data into tables defined in the project from a CSV file or a JSON file.</p><h3>dbt build:</h3><p>This is a key command in DBT both in the Cloud and locally. The dbt build command is used to compile your DBT project and generate artifacts that can be used to run your data pipeline.</p><p>The dbt build command primarily performs three key steps:</p><ol><li>It compiles your DBT project. it parses and compiles all the SQL files in your project, checking for syntax errors and verifying that the code satisfies the DBT conventions and best practices.</li><li>Resolves dependencies: This step checks the ref() statements in your SQL code and resolves them to the appropriate tables/views in your database. It also ensures that dependencies are built in the correct order, so that tables/views are created before they are referenced.</li><li>Generates artifacts: This step generates the SQL code that will be executed in your data warehouse. This includes creating tables/views, loading data, and performing any transformations or calculations. The generated code is saved in the target/ directory of your DBT project.</li></ol><p>The dbt build command is typically run automatically when you deploy your project to DBT Cloud. However, you can also run it manually from the command-line interface if you need to debug or troubleshoot your project.</p><h3>dbt docs generate:</h3><p>While developing your schemas, it is best practice to write the description of each table, column, and data type. With this command, you can automatically generate documentation for the project based on the DBT models and their relationships. The generated documentation is written in Markdown format and is stored in the target directory.</p><h3>dbt debug:</h3><p>If you keep running into errors, running this command will run a debug session and enable users to step through their DBT code and inspect variables.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=650606681aad" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/popular-commands-in-dbt-dej10-650606681aad">Popular commands in DBT: DEJ10</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[Guide to using DBT]]></title>
            <link>https://blog.devgenius.io/guide-to-using-dbt-b9f5e09a670?source=rss-4e93c4cff640------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9f5e09a670</guid>
            <category><![CDATA[dezoomcamp]]></category>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[dbt-models]]></category>
            <dc:creator><![CDATA[Fagbuyi Temitope Emmanuel]]></dc:creator>
            <pubDate>Wed, 22 Feb 2023 08:23:43 GMT</pubDate>
            <atom:updated>2023-02-23T11:52:01.704Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*6eY6nFRlkbAR86y_az9VOA.png" /></figure><p>DBT is a new-age open-source data tool that enables you to transform and model data on a high level. Data engineers use it to optimize their data for reporting and analysis.</p><p>In SAP, the HANA studio is used to create models within the HANA cloud, and IDT is used in BOBJ. Other tools include Archi, LucidChart, PgModeler, etc.</p><p>One key benefit of DBT is it supports versioning with git which makes it easy to track changes your team makes to data models.</p><h3>What language are DBT models written in?</h3><p>DBT models are mostly written in SQL. DBT uses SQL to define data models, transform data, and organize the resulting data sets in a way that is optimized for analytics and reporting.</p><h3>What is Jinja?</h3><p>Jinja is a templating language used in DBT to embed your SQL code into your models. It enables you to define variables and parameters and develop logics that cannot be easily represented with SQL. A jinja code file is saved as an SQL file.</p><p>Here is a simple Jinja code for a dbt model</p><pre>{% set schema = &#39;my_first_dbtmodel&#39;, table_name = &#39;users&#39;%}<br><br>{{<br>config(<br>  materialized = &#39;table&#39;,<br>  schema = schema<br>)<br>}}<br><br>SELECT<br>  id,<br>  name,<br>  email<br>FROM {{ source(&#39;my_source&#39;, table_name) }}<br>WHERE name is NOT NULL</pre><p>In this example, I defined a DBT model that selects a subset of users from a source table called ‘users’ and filters them based on a condition in the WHERE clause.</p><p>Here is a breakdown of the different parts of the model:</p><h4>Variable declaration in Jinja</h4><p>To declare a variable in Jinja, you can use the set function like below.</p><pre>{% set schema = &#39;my_first_dbtmodel&#39; %}</pre><p>You can use this variable later to define the schema where the resulting table will be stored. In the example above, I defined two variables.</p><h4>config materialized in dbt</h4><p>The configmaterialized option in Jinja configures the behavior of the resulting table in your Data Warehouse. The available options depend on the target warehouse and the purpose of the DBT model, but here are the most common options:</p><ol><li>Table: This creates a new table in the target warehouse for the output of the model.</li><li>View: Creates a new view in the target warehouse for the output of the model. If your model do not require significant computational resources, this is a good option.</li><li>Ephemeral: This creates a temporary table in the target warehouse for the output of the model. After each DBT run, the table is automatically dropped. This is a great option for complex and computationally expensive models.</li><li>Incremental: If you have an exisiting model in your target warehouse, this is the config option to use. It updates a pre-existing table in the target warehouse, rather than creating a new table every time the model is run. Also, this is useful for models that require frequent updating.</li><li>Materialized: Allows you to specify a custom materialization for your model. This option is useful if none of the built-in materializations meet your needs, or if you want to reuse a custom materialization across multiple models.</li></ol><p>In the example above:</p><pre>{{config(materialized = &#39;table&#39;)}}</pre><p>In this case, I am setting the materialized parameter to ‘table’, which means that the table will be created in the database. I am also setting the schema parameter to the value of the schema variable we defined earlier.</p><p>Embedding SQL in Jinja</p><pre>SELECT<br>  id,<br>  name,<br>  email<br>FROM {{ source(&#39;my_source&#39;, table_name) }}<br>WHERE name is NOT NULL</pre><p>This is the SQL code that defines the data transformation. It selects the id, name, and email columns from the ‘users’ table — remember, we defined a variable for this.</p><h4>the ‘source’</h4><p>After connecting your DBT to your BigQuery, the ‘source’ defines where your table is located in your DWH.</p><p>For best practice, you should define this in a new schema.yml file entirely that points to your Data Warehouse as below:</p><pre># my_sources.yml<br><br>version: 2<br><br>sources:<br>  - name: my_source<br>    database: &lt;projet-id&gt;<br>    schema: &lt;dwh-dataset&gt;<br>    tables:<br>      - name: users</pre><p>The ‘database’ is will be your BigQuery project ID, and the schema will be the dataset where your tables are, and of course, the table ‘users’ should be in your data warehouse.</p><p>In our example, this function returns a reference to the table that can be used in the SQL code.</p><h3>The DBT interface</h3><p>When you initialize a new dbt model, you should have this interface on your right side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*lDCbR8ek1-dKQzasXkBQuw.png" /></figure><h4>The models folder:</h4><p>This folder contains the SQL code that defines dbt models. Do note that a dbt model is a definition of a transformation of data from one or more source tables to a destination table.</p><p>The models folder typically includes one or more subfolders that group models based on their purpose or functionality. For example, your project might have separate subfolders for prod, dev, and test systems models, which define the data for the various systems.</p><h4>The macros folder:</h4><p>Macros in DBT codes are simply lumps of reusable codes that can be used across various models. The macros folder holds your macros. Macros are defined in separate files and are then made available to models via the {% macro %} tag.</p><p>Example below:</p><pre>{% macro my_macro(my_param) %}<br><br>    select * from my_table <br>    where column_name = {{ my_param }}<br><br>{% endmacro %}</pre><p>To call this macro in a model, you can use the “{{ }} syntax to pass the parameter to the macro like this:</p><p>{{ my_macro(my_param=’some_value’) }}</p><h4>The target folder</h4><p>The target folder contains all the compiled SQL codes of each dbt model you run. The codes are arranged into materialized form (tables, incremental, views, ephemeral, etc) folders and according to the model name.</p><p>Each code is generated when you run a DBT model. It gives you the full and holistic detail of your SQL code in the model. Hence, if you have several macros, variables, or packages in your model, the code generated in the target folder compiles it all into a condensed code that lets you see how your code runs without the dependencies.</p><h4><strong>The Seeds folder</strong></h4><p>Seeds in dbt are usually small reference data that do not change often you want to load directly into your DWH. Your seed file can be a YAML file or a CSV file and they are contained in the Seeds folder. To load the data into the DWH, you can use the dbt seed command</p><h3>Conclusion</h3><p>DBT is a software tool that data engineers use to transform and model data for reporting and analysis. It’s open-source, meaning anyone can use it for free. With DBT, engineers write SQL code to define data models, which can then be optimized and versioned using Git. There are also reusable code snippets called macros, which make it easy to share functionality across different models. DBT offers various materialization options, such as tables or views, which enable customization of the resulting tables in a data warehouse. By streamlining the data transformation process, DBT makes it easier and more efficient for data engineers to work with data in their organizations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9f5e09a670" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/guide-to-using-dbt-b9f5e09a670">Guide to using DBT</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[Setting up your dbt cloud: DEJ 9]]></title>
            <link>https://medium.com/@tofag/setting-up-your-dbt-cloud-dej-9-d18e5b7c96ba?source=rss-4e93c4cff640------2</link>
            <guid isPermaLink="false">https://medium.com/p/d18e5b7c96ba</guid>
            <category><![CDATA[dezoomcamp]]></category>
            <category><![CDATA[dbt-cloud]]></category>
            <category><![CDATA[data-modelling]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Fagbuyi Temitope Emmanuel]]></dc:creator>
            <pubDate>Sun, 19 Feb 2023 12:39:10 GMT</pubDate>
            <atom:updated>2023-02-19T12:41:11.573Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LfeTCj4-Tq2P3z7d.png" /></figure><p><em>Aside: This series on Data Engineering will be quite personal and will be a walkthrough of my journey with the </em><a href="https://github.com/DataTalksClub/data-engineering-zoomcamp"><em>#dezoomcamp data engineering</em></a><em> training. NB: Kindly leave your comments and corrections if you find this educating or misleading, I won’t hesitate to make amendment(s).</em></p><h3>What is DBT?</h3><p>DBT, also known as the Data Build Tool, is a popular data modeling and transformation tool. It is open-source and quite popular as the latest data stack tool. It is used from the CLI and allows data analysts and engineers to model data into an optimized version for analytics and reporting.</p><p>DBT enables you to define data models in SQL and then build, test, and deploy those models as part of a repeatable data pipeline.</p><p>In this article, we will set up a DBT cloud account, using BigQuery as our data warehouse. The DBT cloud lets you perform complicated models on the data in your BigQuery all from your browser.</p><p>There is also an option to use it locally, which will require you download the file on your PC.</p><ol><li>Create a free account on <a href="https://www.getdbt.com/product/what-is-dbt/">https://www.getdbt.com/product/what-is-dbt/</a></li><li>Verify your account</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SL06LKWi3J8J4iNZ40ixqQ.png" /></figure><p>Name your project and choose a warehouse, in this regard — Big Query and click Next</p><p>Configure your environment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8juiU3neMkp2uWyzvardw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*l0udtVmUsHGiJ0Kgf5V7-w.png" /></figure><p>Uploading your service account credentials will automatically fill the subsequent field. You can manually add the URL of the GCS bucket you want to connect to your dbt account.</p><p>After that, test your connection and set up a repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPLAufdR3xTreKZAiKmp6A.png" /></figure><p>Once you have decided on the repository, — I will be using the dbt repo — click next and get started.</p><p>Your page should be similar to this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FyGWJXAStUskV6DOTLB7Fg.png" /></figure><p>On the left side,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*6pQyC9J20pdlAh2N0NIOnQ.png" /></figure><p>The model folder contains all your models. You can create new models by clicking the three dots.</p><p>The seeds folder contains all your DBT seeds. DBT seeds are a type of model that allows you to load data from external sources, such as CSV files, into your data warehouse. Seeds are mainly used to provide reference data that doesn’t change often, like a list of cities or product categories, or to simulate data that are not available in a production environment.</p><p>The macros folder contains all your macros. DBT macros are simply reusable codes that you call repeatedly in your model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d18e5b7c96ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Lake vs Data Warehouse. DEJ: Part 8]]></title>
            <link>https://medium.com/@tofag/data-lake-vs-data-warehouse-dej-part-8-755a7a4d5a30?source=rss-4e93c4cff640------2</link>
            <guid isPermaLink="false">https://medium.com/p/755a7a4d5a30</guid>
            <category><![CDATA[dezoomcamp]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-lake]]></category>
            <dc:creator><![CDATA[Fagbuyi Temitope Emmanuel]]></dc:creator>
            <pubDate>Mon, 13 Feb 2023 08:20:36 GMT</pubDate>
            <atom:updated>2023-02-13T08:20:36.796Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/318/0*jAqYxiz_CLFRHkUg" /></figure><p><em>Aside: This series on Data Engineering will be quite personal and will be a walkthrough of my journey with the </em><a href="https://github.com/DataTalksClub/data-engineering-zoomcamp"><em>#dezoomcamp data engineering</em></a><em> training. NB: Kindly leave your comments and corrections if you find this educating or misleading, I won’t hesitate to make amendment(s).</em></p><p>Despite there being several ways for organizations to store and manage large amounts of data, data lakes, and data warehouses are the most popular. It is quite easy to confuse the two together, especially for beginners. However, their differences lie in their design and the kind of data they store.</p><h3>What is a Data Lake?</h3><p>A data lake is a vast, centralized repository that stores large amounts of data, both raw and structured. The data is stored in its native format, without any restrictions or constraints, making it easy to store and access.</p><p>The data lake is where organizations ‘pour’ data as it comes, raw and without cleaning. This allows organizations to perform advanced analytics and machine learning on these data.</p><p>Data Lakes are cheap and allow a massive amount of data to reside in them at a whim.</p><h4>Example of Data Lakes</h4><p>The most popular solution by cloud providers that can be used as a data lake include:</p><ol><li>Amazon S3: Amazon S3 is a highly scalable, object storage service offered by Amazon Web Services (AWS). It can be used as a data lake, as it allows organizations to store and analyze large amounts of raw and structured data from a variety of sources.</li><li>Microsoft Azure Data Lake Storage: Microsoft Azure Data Lake Storage is a cloud-based data lake solution that allows organizations to store and analyze large amounts of data in its native format. It is designed to be scalable, secure, and cost-effective.</li><li>Google Cloud Storage: Google Cloud Storage is a highly scalable, object storage service offered by Google Cloud. It can be used as a data lake, as it allows organizations to store and analyze large amounts of raw and structured data from a variety of sources.</li></ol><h3>What is a Data Warehouse?</h3><p>A data warehouse is simply a relational database (i.e data is stored in rows and columns) designed to store and manage large amounts of structured data.</p><p>Data warehouses are optimized for fast query performance and business intelligence reporting, since the data in the data warehouse is structured, they are easy to analyze and visualize.</p><p>Before loading data into the Data Warehouse, the data is usually subjected to a series of transformations and cleaning to ensure the quality of data is consistent.</p><h4>Examples of data warehouses:</h4><ol><li>Amazon Redshift: Amazon Redshift is a fully managed data warehouse service offered by Amazon Web Services (AWS). It allows organizations to store and analyze large amounts of structured data and is optimized for fast query performance and business intelligence reporting.</li><li>Microsoft Azure Synapse Analytics (formerly SQL Data Warehouse): Microsoft Azure Synapse Analytics is a cloud-based data warehousing solution that combines big data and data warehousing into a single service. It provides organizations with a single source of truth for their data and allows them to perform advanced analytics and reporting.</li><li>Google BigQuery: Google BigQuery is a cloud-based data warehousing solution that allows organizations to store and analyze large amounts of structured data. It is designed to be fast and scalable and provides organizations with a single source of truth for their data</li><li>SAP BW (SAP Business Warehouse): SAP BW is a popular data warehousing solution that organizations use to store, manage, and analyze large amounts of structured data. SAP BW provides a single source of truth for an organization’s data and is optimized for fast query performance and business intelligence reporting.</li></ol><h3>Differences between a Data Lake and a Data Warehouse:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*DGB26Y4idXa3mkRT2ehYPg.png" /></figure><h3>Honorable Mention: Data Lakehouse</h3><p>A data lakehouse is a combination of a data lake and a data warehouse. It combines the scalable, flexible architecture of a data lake with the structured, optimized data storage and querying capabilities of a data warehouse.</p><p>A data lakehouse allows organizations to store and process large volumes of both structured and unstructured data in its native format, and then selectively structure the data for faster querying and analysis. This enables organizations to quickly turn raw data into valuable insights and make data-driven decisions.</p><p>A data lakehouse also provides a centralized repository for storing data from multiple sources, making it easier for organizations to manage and govern their data assets. With a data lakehouse, data can be easily accessed by data scientists, business analysts, and other stakeholders, while still maintaining the security and governance controls required for sensitive data.</p><h3>Conclusion</h3><p>Both data lakes and data warehouses have their own unique advantages and disadvantages. The choice between the two will depend on the specific requirements of an organization and the type of data they need to store and manage. Data warehouses are ideal for organizations that need to store and analyze structured data, while data lakes are better suited for organizations that need to store and analyze a wide range of data types. Ultimately, the choice between a data lake and a data warehouse will depend on the specific needs and goals of the organization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=755a7a4d5a30" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>