<?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 Daniel Ruiz on Medium]]></title>
        <description><![CDATA[Stories by Daniel Ruiz on Medium]]></description>
        <link>https://medium.com/@theblogofdaniel?source=rss-13aade437760------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*6nrQ62_KnRnhUPtQ3Zuy3g.png</url>
            <title>Stories by Daniel Ruiz on Medium</title>
            <link>https://medium.com/@theblogofdaniel?source=rss-13aade437760------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:28:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@theblogofdaniel/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[34 Things I Wished I Knew Before My Databricks ML Associate Exam]]></title>
            <link>https://medium.com/@theblogofdaniel/34-things-i-wished-i-knew-before-my-databricks-ml-associate-exam-49113d261ad8?source=rss-13aade437760------2</link>
            <guid isPermaLink="false">https://medium.com/p/49113d261ad8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[databricks-certification]]></category>
            <dc:creator><![CDATA[Daniel Ruiz]]></dc:creator>
            <pubDate>Fri, 01 Dec 2023 06:53:15 GMT</pubDate>
            <atom:updated>2023-12-01T06:53:15.742Z</atom:updated>
            <content:encoded><![CDATA[<p>Databricks is one of the most powerful data platforms out there. It combines a Data Platform and an AI Platform into the extremely powerful <a href="https://www.databricks.com/product/data-intelligence-platform">Databricks Data Intelligence Platform</a>, that enables organizations to capture the true potential of their data and their data teams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*do1ktvGR9Cj6vzFBu_8Irw.png" /></figure><p>To enable users to make the most of its countless features, Databricks has opened <a href="https://www.databricks.com/blog/2022/09/09/getting-databricks-certified-now-easier-free-overview-courses.html">free overview courses</a> to partners and customers in the Databricks Academy. These courses are linked to paid certifications targeting different roles, including for ML professionals. These courses and certification paths are a great way of learning more about Databricks.</p><p>There are two relevant Databricks certifications for Machine Learning:</p><ul><li>Machine Learning Associate</li><li>Machine Learning Professional</li></ul><p>Often, these are pursued by Machine Learning Engineers (of all flavours including MLOPS) and Data Scientists that want to prove their Databricks expertise, and acquire a more comprehensive view of what the platform offers.</p><p>This was the case for me. I am a Machine Learning Engineer. While preparing for the Machine Learning Associate certification, I noticed the lack of good public content out there to prepare candidates for the certification. I’ve passed the certification, and written this article to help you conquer your badge too.</p><p>This article covers relevant topics for the Associate certification. This is not an introduction to Machine Learning or Databricks; rather, this is a topic review for the Databricks Machine Learning Associate certification. Be <em>sharp </em>on the following topics before taking the exam.</p><h3>The Exam</h3><p>To obtain the Databricks <a href="https://www.databricks.com/learn/certification/machine-learning-associate">Machine Learning Associate</a> certification, you need to pass an online-proctored exam. The certification is intended for professionals with at least six-month experience in the platform, and it’s valid for 2 years.</p><p>In under 90 minutes, you will need to achieved a 70% mark on 45 questions. Some of these questions focus on code and the Databricks platform, some on modelling and theoretical Machine Learning concepts.</p><p>The exam is only available in English.</p><p>It is divided in four sections with the following weights and topics:</p><ol><li><strong>Databricks Machine Learning (29%):</strong> Databricks ML, Databricks Runtime for Machine Learning, AutoML, Feature Store, Managed MLflow</li><li><strong>ML Workflows (29%):</strong> Exploratory Data Analysis, Feature Engineering, Training, Evaluation and Selection</li><li><strong>Spark ML (33%):</strong> Distributed ML Concepts, Spark ML Modelling APIs, Hyperopt, Pandas API on Spark, Pandas UDFs/Function APIs</li><li><strong>Scaling ML Models (9%):</strong> Model Distribution, Ensembling Distribution</li></ol><p>More details are available in the official <a href="https://files.training.databricks.com/static/docs/databricks-certified-machine-learning-associate-exam-guide.pdf?_gl=1*1fvzpey*_gcl_aw*R0NMLjE3MDAwNDc0MjQuQ2p3S0NBaUE5ZEdxQmhBcUVpd0FtUnBUQzhseU1SNnNFUzl0UVlMcXBhaXAzb0h3U2lxTVN6UEN4ZWpVcjU3WHBaN1d0ZGlBaG1rWkp4b0NyaWNRQXZEX0J3RQ..*_gcl_au*MzYyNzAwMTE2LjE2OTYyMzkxMjQ.*rs_ga*MmQ5NjI0YjMtYzQwOS00OTUxLTlmMzgtYTc4Y2FhOTBlNzE3*rs_ga_PQSEQ3RZQC*MTcwMDA0NzQxNjI1Ni4zNy4xLjE3MDAwNDc0MzQuNTAuMC4w">Exam Guide</a>.</p><h3>Databricks Machine Learning</h3><h4>1. How to integrate Git and Databricks to deliver CI/CD?</h4><p><a href="https://docs.databricks.com/en/repos/ci-cd-techniques-with-repos.html">Databricks </a>provides the following overview on how to integrate Git repos with Databricks Repos, and hence provide source control for project files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*NdxbIBHMM7u3mI7Z.png" /></figure><h4>2. When is a single-node cluster preferred?</h4><p>Databricks clusters may be <a href="https://learn.microsoft.com/en-us/azure/databricks/clusters/cluster-config-best-practices">multi-node or single-node</a>.</p><blockquote>Single Node clusters are intended for jobs that use small amounts of data or non-distributed workloads such as single-node machine learning libraries.</blockquote><blockquote>Multi Node clusters are for larger jobs with distributed workloads.</blockquote><h4>3. Which libraries are included in Databricks Runtime ML?</h4><p>The Databricks Runtime is the set of core components that run on compute clusters, and it needs to be selected when <a href="https://docs.databricks.com/en/clusters/configure.html#databricks-runtime-versions">creating the cluster</a>. It comes in different versions.</p><p>There is a specialized runtime for Machine Learning. These have an ML suffix (e.g. Databricks Runtime 14.1 ML), and include include a series of relevant libraries. Databricks designates a few of these libraries as top tier, and these are updated to the latest package available at every new runtime (if there are no dependency conflicts).</p><p>The <a href="https://docs.databricks.com/en/release-notes/runtime/14.1ml.html">Databricks Runtime 14.1 ML</a> includes the following top-tier libraries:</p><ul><li><a href="https://docs.databricks.com/en/integrations/graphframes/index.html">GraphFrames</a></li><li><a href="https://docs.databricks.com/en/machine-learning/train-model/distributed-training/index.html">Horovod and HorovodRunner</a></li><li><a href="https://docs.databricks.com/en/mlflow/index.html">MLflow</a></li><li><a href="https://docs.databricks.com/en/machine-learning/train-model/pytorch.html">PyTorch</a></li><li><a href="https://docs.databricks.com/en/machine-learning/load-data/tfrecords-save-load.html#df-to-tfrecord">spark-tensorflow-connector</a></li><li><a href="https://docs.databricks.com/en/machine-learning/train-model/tensorflow.html">TensorFlow</a></li><li><a href="https://docs.databricks.com/en/machine-learning/train-model/tensorboard.html">TensorBoard</a></li><li><a href="https://docs.databricks.com/en/machine-learning/train-model/scikit-learn.html">Scikit-learn</a></li></ul><h4>4. How to install additional libraries to a cluster?</h4><p>Databricks lists seven different ways of <a href="https://docs.databricks.com/en/libraries/cluster-libraries.html">installing a library to a cluster</a>.</p><ul><li>Install a library for use with a specific cluster only.</li><li>Install a workspace library that has previously been defined in the <a href="https://docs.databricks.com/en/libraries/workspace-libraries.html">workspace</a>.</li><li>Install a library with the <a href="https://docs.databricks.com/api/workspace/libraries/install">REST API</a>.</li><li>Install a library with the <a href="https://docs.databricks.com/en/dev-tools/cli/index.html">Databricks CLI</a>.</li><li>Install a library using <a href="https://docs.databricks.com/en/dev-tools/terraform/index.html">Databricks Terraform</a>.</li><li>Install a library by creating a cluster with a <a href="https://docs.databricks.com/en/administration-guide/clusters/policies.html">policy</a> that defines library installations.</li><li>Install a library using an <a href="https://docs.databricks.com/en/archive/compute/libraries-init-scripts.html">init script</a> that runs at cluster creation time (not recommended).</li></ul><p>The <a href="https://docs.databricks.com/en/archive/compute/libraries-init-scripts.html">current preferred solution</a> is using cluster policies. The init script, though widely used in industry, is no longer recommended by Databricks. Indeed, Databricks recommends replacing installation via init scripts with cluster policies.</p><h4>5. What can Databricks AutoML do?</h4><p><a href="https://docs.databricks.com/en/machine-learning/automl/index.html">Databricks AutoML</a> <a href="https://www.databricks.com/fr/product/automl">enables Data Scientists</a> to quickly generate baseline <em>models</em> and <em>notebooks</em> with a low-code approach. Then, citizen data scientists may use their domain knowledge to customize and improve these baselines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SjSBhRiKlHYTGhkt.png" /></figure><p>More pragmatically, it will perform the following <a href="https://docs.databricks.com/en/machine-learning/automl/how-automl-works.html">machine learning tasks</a> given an input <em>dataset</em> and <em>target column</em>:</p><blockquote>1. AutoML prepares the dataset for model training.</blockquote><blockquote>2. AutoML then performs and records a set of trials that creates, tunes, and evaluates multiple models.</blockquote><blockquote>3. AutoML displays the results and provides a Python notebook with the source code for each trial run so you can review, reproduce, and modify the code.</blockquote><blockquote>4. AutoML also calculates summary statistics on your dataset and saves this information in a notebook that you can review later.</blockquote><h4>6. What evaluation metrics are optimized by Databricks AutoML?</h4><p>Databricks AutoML accepts three use-cases: <a href="https://docs.databricks.com/en/machine-learning/automl/train-ml-model-automl-api.html#classification">classification</a>, <a href="https://docs.databricks.com/en/machine-learning/automl/train-ml-model-automl-api.html#regression">regression</a>, and <a href="https://docs.databricks.com/en/machine-learning/automl/train-ml-model-automl-api.html#forecasting">forecasting</a>. Each use-case accepts a set of evaluation metrics.</p><ul><li><strong>Regression:</strong> r2 (default), mae, rmse, or mse.</li><li><strong>Classification:</strong> f1 (default), log_loss, precision, accuracy, or roc_auc.</li><li><strong>Forecasting:</strong> smape (default), mse, rmse, mae, or mdape.</li></ul><p>In the example below, AutoML is used programmatically to run a regression that minimizes the root mean squared error:</p><pre>from databricks import automl<br><br>summary = automl.regress(train_df<br>                          , target_col=&quot;price&quot;<br>                          , primary_metric=&quot;rmse&quot;<br>                          , timeout_minutes=5<br>                          , max_trials=10)<br><br>print(summary.best_trial)</pre><p>In this second example, AutoML maximizes the f1-score of a classification problem:</p><pre>from databricks import automl<br><br>summary = automl.classify(train_df<br>                          , target_col=&quot;income&quot;<br>                          , primary_metric=&quot;f1&quot;<br>                          , timeout_minutes=30)<br><br>print(summary.best_trial)</pre><h4>7. How to orchestrate multi-task Databricks jobs?</h4><p><a href="https://docs.databricks.com/en/workflows/index.html">Databricks Workflow</a> may execute jobs and tasks either in parallel or sequentially by leveraging dependencies.</p><ul><li>A Databricks job may be used to run data processing and analysis applications in a Databricks workspace.</li><li><em>Jobs</em> are composed of one or more <em>tasks</em> (i.e. multi-task).</li><li>A task may do different things, such as <em>run notebooks, JARS, Delta Live Tables pipelines, or Python, Scala, Spark submit, and Java applications</em>.</li><li>Tasks may have dependencies; these may be used to determine <em>in which order</em> the notebooks will be executed. For example, a job comprised of two tasks — each running a different Databricks notebook — may have these notebooks executed parallelly or sequentially, depending on how the dependencies are configured. This is made clear by the <a href="https://docs.databricks.com/en/workflows/jobs/settings.html">example below</a>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/0*sHrIuLhAwKZ5wFh6.png" /></figure><h4>8. What is a Feature Store?</h4><p>According to <a href="https://docs.databricks.com/en/machine-learning/feature-store/index.html">Databricks</a>:</p><blockquote>A feature store is a centralized repository that enables data scientists to find and share features and also ensures that the same code used to compute the feature values is used for model training and inference.</blockquote><p><a href="https://docs.databricks.com/en/machine-learning/feature-store/index.html#feature-engineering-in-unity-catalog">Unit Catalog</a> becomes your feature store if (i) Unity Catalog has been enabled and (ii) runtime is 13.2 or above. In summary:</p><blockquote>For workspaces that are enabled for Unity Catalog, <a href="https://docs.databricks.com/en/machine-learning/feature-store/uc/feature-tables-uc.html#create-feature-table">write the DataFrame as a feature table in Unity Catalog</a>.</blockquote><blockquote>If your workspace is not enabled for Unity Catalog, <a href="https://docs.databricks.com/en/machine-learning/feature-store/workspace-feature-store/feature-tables.html#create-feature-table">write the DataFrame as a feature table in the Workspace Feature Store</a>.</blockquote><p>To <a href="https://docs.databricks.com/en/machine-learning/feature-store/workspace-feature-store/feature-tables.html">create a feature table</a> in a feature store:</p><pre>from databricks.feature_store import feature_table<br><br>def compute_customer_features(data):<br>  &#39;&#39;&#39; Feature computation code returns a DataFrame with &#39;customer_id&#39; as primary key&#39;&#39;&#39;<br>  pass<br><br># create feature table keyed by customer_id<br># take schema from DataFrame output by compute_customer_features<br>from databricks.feature_store import FeatureStoreClient<br><br>customer_features_df = compute_customer_features(df)<br><br>fs = FeatureStoreClient()<br><br>customer_feature_table = fs.create_table(<br>  name=&#39;recommender_system.customer_features&#39;,<br>  primary_keys=&#39;customer_id&#39;,<br>  schema=customer_features_df.schema,<br>  description=&#39;Customer features&#39;<br>)<br><br># An alternative is to use `create_table` and specify the `df` argument.<br># This code automatically saves the features to the underlying Delta table.<br><br># customer_feature_table = fs.create_table(<br>#  ...<br>#  df=customer_features_df,<br>#  ...<br># )<br><br># To use a composite key, pass all keys in the create_table call<br><br># customer_feature_table = fs.create_table(<br>#   ...<br>#   primary_keys=[&#39;customer_id&#39;, &#39;date&#39;],<br>#   ...<br># )</pre><p>To register an existing delta table as a feature table:</p><pre>fs.register_table(<br>  delta_table=&#39;recommender.customer_features&#39;,<br>  primary_keys=&#39;customer_id&#39;,<br>  description=&#39;Customer features&#39;<br>)</pre><p>To write data to an existing table:</p><pre># Use write_table to write data to the feature table<br># overwrite mode does a full refresh of the feature table<br># merge mode updates only specific rows in a feature table<br>fs.write_table(<br>  name=&#39;recommender_system.customer_features&#39;,<br>  df = customer_features_df,<br>  mode = &#39;overwrite&#39;<br>)</pre><p>To read from a feature table:</p><pre>fs = feature_store.FeatureStoreClient()<br>customer_features_df = fs.read_table(name=&#39;recommender.customer_features&#39;)</pre><p>Finally, to get its metadata:</p><pre># this example works with v0.3.6 and above<br># for v0.3.5, use `get_feature_table`<br>from databricks.feature_store import FeatureStoreClient<br>fs = FeatureStoreClient()<br>fs.get_table(&quot;feature_store_example.user_feature_table&quot;)</pre><h4>9. How to take a feature from Feature Store?</h4><p>Assuming the Feature Store has been created correctly, it’s necessary to create a Feature Store client and do a feature lookup.</p><p>In a <a href="https://docs.databricks.com/en/machine-learning/feature-store/train-models-with-feature-store.html#language-Workspace%C2%A0Feature%C2%A0Store">simple example</a>:</p><pre>from databricks.feature_store import FeatureLookup, FeatureStoreClient<br><br>feature_lookups = [<br>    FeatureLookup(<br>      table_name=&#39;recommender_system.customer_features&#39;,<br>      feature_names=[&#39;interests&#39;],<br>      lookup_key=&#39;customer_id&#39;,<br>    ),<br>  ]<br><br>fs = FeatureStoreClient()<br>with mlflow.start_run():<br>  training_set = fs.create_training_set(<br>    df=df,<br>    feature_lookups=feature_lookups,<br>    label=None,<br>    exclude_columns=[&#39;customer_id&#39;]<br>  )<br><br>  training_df = training_set.load_df()</pre><p>In a <a href="https://learn.microsoft.com/en-us/azure/databricks/machine-learning/feature-store/train-models-with-feature-store">more developed example</a>:</p><pre>from databricks.feature_store import FeatureLookup, FeatureStoreClient<br><br># The model training uses two features from the &#39;customer_features&#39; feature table and<br># a single feature from &#39;product_features&#39;<br>feature_lookups = [<br>    FeatureLookup(<br>      table_name=&#39;recommender_system.customer_features&#39;,<br>      feature_names=[&#39;total_purchases_30d&#39;, &#39;total_purchases_7d&#39;],<br>      lookup_key=&#39;customer_id&#39;<br>    ),<br>    FeatureLookup(<br>      table_name=&#39;recommender_system.product_features&#39;,<br>      feature_names=[&#39;category&#39;],<br>      lookup_key=&#39;product_id&#39;<br>    )<br>  ]<br><br>fs = FeatureStoreClient()<br><br># Create a training set using training DataFrame and features from Feature Store<br># The training DataFrame must contain all lookup keys from the set of feature lookups,<br># in this case &#39;customer_id&#39; and &#39;product_id&#39;. It must also contain all labels used<br># for training, in this case &#39;rating&#39;.<br>training_set = fs.create_training_set(<br>  df=training_df,<br>  feature_lookups=feature_lookups,<br>  label=&#39;rating&#39;,<br>  exclude_columns=[&#39;customer_id&#39;, &#39;product_id&#39;]<br>)<br><br>training_df = training_set.load_df()</pre><p>If <em>feature_names</em> is not specified in the <em>FeatureLookup</em>, then all features except primary keys will be taken.</p><p><a href="https://docs.databricks.com/en/_extras/notebooks/source/machine-learning/feature-store-time-series-example.html">This notebook</a> provides an good implementation of Feature Stores, and also shows how to do batch scoring.</p><h4>10. How to log an artifact using MLflow?</h4><p>As stated in <a href="https://mlflow.org/docs/latest/tracking.html">MLflow documentation</a>:</p><blockquote>The MLflow Tracking component is an API and UI for logging parameters, code versions, metrics, and output files when running your machine learning code and for later visualizing the results.</blockquote><p>The <em>log_artifact </em>function may be used to log artifacts such as a DataFrame in the model folder. <a href="https://mlflow.org/docs/latest/python_api/mlflow.html#mlflow.log_artifact">The function accepts the following parameters</a>:</p><pre>mlflow.log_artifact(local_path: str<br>                    , artifact_path: Optional[str] = None<br>                    ) → None</pre><p>Three important takeaways are:</p><ul><li>There is only one required parameter (<em>local_path</em>), and it is a <em>path</em> that points to a <em>file</em>.</li><li>If instead a <em>folder </em>is to be logged, the function <em>log_artifacts</em> should be used.</li><li>The optional parameter <em>artifact_path </em>points to a folder in the <em>artifact_uri</em> where to write the artifact to.</li></ul><p>The following snippet illustrates usage in a simple case:</p><pre>import mlflow<br><br># Create a features.txt artifact file<br>features = &quot;rooms, zipcode, median_price, school_rating, transport&quot;<br>with open(&quot;features.txt&quot;, &quot;w&quot;) as f:<br>    f.write(features)<br><br># With artifact_path=None write features.txt under<br># root artifact_uri/artifacts directory<br>with mlflow.start_run():<br>    mlflow.log_artifact(&quot;features.txt&quot;)</pre><h4>11. How to get the best run of a model using MLflow?</h4><p>It’s possible to use the MLflow Tracking API to <a href="https://www.databricks.com/blog/2020/02/18/how-to-display-model-metrics-in-dashboards-using-the-mlflow-search-api.html">search runs</a>, and conveniently return results in the form of a DataFrame.</p><p>What does <em>best</em> mean? In this context, it will be the run that optimizes the metric specified. For example: what’s the run that <em>minimizes</em> the mean average error (MAE)?</p><pre>runs = mlflow.search_runs(experiment_ids=experiment_id,<br>                          order_by=[&#39;metrics.mae&#39;],<br>                          max_results=1)<br>runs.loc[0]</pre><h3>ML Workflows</h3><h4>12. How to filter a Spark DataFrame on a given column?</h4><p><a href="https://www.geeksforgeeks.org/pyspark-filter-dataframe-based-on-multiple-conditions/">GeeksForGeeks</a> lists different ways of filtering Spark DataFrames using the <em>filter</em> method.</p><p>Using filter() alone:</p><pre>dataframe.filter(dataframe.college == &#39;DU&#39;)</pre><p>Or, combining filter() with SQL col():</p><pre>dataframe.filter(col(&#39;college&#39;) == &#39;DU&#39;)</pre><p>The <em>where</em> method is also handy.</p><pre>dataframe.where(dataframe.college == &#39;DU&#39;) </pre><p>Also with col():</p><pre>dataframe.where(col(&#39;college&#39;) == &#39;DU&#39;)</pre><p>A couple extra points:</p><ul><li>If used altogether with inequality signs, these methods may be used to remove outliers from your dataset.</li><li>Using col() is <a href="https://github.com/palantir/pyspark-style-guide">generally preferred</a> to not using it.</li></ul><h4>13. How to use dbutils.data.summarize?</h4><p><a href="https://learn.microsoft.com/en-us/azure/databricks/dev-tools/databricks-utils">Microsoft</a> explains that the <em>summarize</em> command calculates and displays summary statistics of an Apache Spark DataFrame or pandas DataFrame.</p><p>This command is available for Python, Scala and R.</p><p>This command may receive the <em>precise</em> parameter (default is False).</p><ul><li>When set to <strong>False</strong>, execution is faster, but that comes at the expense of a higher relative error.</li><li>When set to <strong>True</strong>, all statistics except for the histograms and percentiles for numeric columns are exact. The histograms and percentile estimates may have an error of up to 0.0001% relative to the total number of rows.</li></ul><p>In Python:</p><pre>df = spark.read<br>          .format(&#39;csv&#39;)<br>          .load(&#39;/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv&#39;, header=True, inferSchema=True)<br><br>dbutils.data.summarize(df)</pre><p>In Spark:</p><pre>val df = spark.read<br>              .format(&quot;csv&quot;)<br>              .option(&quot;inferSchema&quot;, &quot;true&quot;)<br>              .option(&quot;header&quot;, &quot;true&quot;)<br>              .load(&quot;/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv&quot;)<br><br>dbutils.data.summarize(df)</pre><p>In R:</p><pre>df &lt;- read.df(&quot;/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv&quot;, source = &quot;csv&quot;, header=&quot;true&quot;, inferSchema = &quot;true&quot;)<br><br>dbutils.data.summarize(df)</pre><h4>14. How to use summary?</h4><p>The <a href="https://spark.apache.org/docs/3.1.2/api/python/reference/api/pyspark.sql.DataFrame.summary.html"><em>summary</em> command</a> is also quite handy. It provides the basic statistics from a Spark DataFrame.</p><pre>df.summary().show()<br><br>+-------+------------------+-----+<br>|summary|               age| name|<br>+-------+------------------+-----+<br>|  count|                 2|    2|<br>|   mean|               3.5| null|<br>| stddev|2.1213203435596424| null|<br>|    min|                 2|Alice|<br>|    25%|                 2| null|<br>|    50%|                 2| null|<br>|    75%|                 5| null|<br>|    max|                 5|  Bob|<br>+-------+------------------+-----+</pre><h4>15. How to input missing values?</h4><p>The <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.feature.Imputer.html"><em>imputer</em> class</a> may be used to input missing values using either the mean, median, or mode of a variable. The <em>imputer</em> does not support categorical features, only numeric features. It’s still possible to input categorial variables, but first it needs be converted to a numerical label.</p><p>The mean and median are frequently used to input missing numeric values, and the mode is used to input categorical values that have been converted to numeric. By default, the mean is used as imputation strategy.</p><p>For example:</p><pre>from pyspark.ml.feature import Imputer<br><br>df = spark.createDataFrame([(1.0, float(&quot;nan&quot;)), (2.0, float(&quot;nan&quot;)), (float(&quot;nan&quot;), 3.0),<br> (4.0, 4.0), (5.0, 5.0)], [&quot;a&quot;, &quot;b&quot;])<br><br>imputer = Imputer(inputCols=[&quot;a&quot;, &quot;b&quot;],<br>                  outputCols=[&quot;out_a&quot;, &quot;out_b&quot;],<br>                  strategy=&quot;mean&quot;)<br><br>model = imputer.fit(df)<br>model.transform(df)</pre><p>One disclaimer: before inputting a missing value, it’s important to evaluate whether this is a good idea from a modelling perspective. Maybe, the model should see the missing values and learn from them.</p><h4>16. How to deal with missing data in tree algorithms?</h4><p>As <a href="https://www.ibm.com/topics/decision-trees.">IBM explains</a>, Decision Trees require little to no data preparation. They handle both discrete and continuous variables, and they may also handle variables with missing values.</p><p>Databricks generally favours letting missing values be missing, and let tree algorithms figure their way around them.</p><h4>17. How to index and one hot encode categorical variables?</h4><p>Usually, categorical variables come as string. If that’s the case, the first step is to use the <a href="https://spark.apache.org/docs/latest/ml-features#stringindexer">StringIndexer</a> to represent this feature as numerical.</p><pre>from pyspark.ml.feature import StringIndexer<br><br>df = spark.createDataFrame(<br> [(0, “a”), (1, “b”), (2, “c”), (3, “a”), (4, “a”), (5, “c”)],<br> [“id”, “category”])<br><br>indexer = StringIndexer(inputCol=”category”, outputCol=”categoryIndex”)<br>indexed = indexer.fit(df).transform(df)<br>indexed.show()</pre><p>Then, the second step is to apply the <a href="https://spark.apache.org/docs/latest/ml-features#onehotencoder">OneHotEncoder</a></p><pre>from pyspark.ml.feature import OneHotEncoder:<br>encoder = OneHotEncoder(inputCols=[“categoryIndex”], outputCols=[“categoryVec”])<br><br>model = encoder.fit(indexed)<br>encoded = model.transform(indexed)<br>encoded.show()</pre><h4>18. How to use the VectorAssembler?</h4><p>According to Apache Spark <a href="https://spark.apache.org/docs/latest/ml-features#vectorassembler">documentation</a>:</p><blockquote>[The] VectorAssembler is a transformer that combines a given list of columns into a single vector column. It is useful for combining raw features and features generated by different feature transformers into a single feature vector, in order to train ML models like logistic regression and decision trees.</blockquote><p>This is illustrated in the example below:</p><pre>from pyspark.ml.linalg import Vectors<br>from pyspark.ml.feature import VectorAssembler<br><br>dataset = spark.createDataFrame(<br> [(0, 18, 1.0, Vectors.dense([0.0, 10.0, 0.5]), 1.0)],<br> [“id”, “hour”, “mobile”, “userFeatures”, “clicked”])<br><br>assembler = VectorAssembler(<br> inputCols=[“hour”, “mobile”, “userFeatures”],<br> outputCol=”features”)<br><br>output = assembler.transform(dataset)<br>print(“Assembled columns ‘hour’, ‘mobile’, ‘userFeatures’ to vector column ‘features’”)<br>output.select(“features”, “clicked”).show(truncate=False)<br><br># id | hour | mobile | userFeatures | clicked | features<br># — — | — — — | — — — — | — — — — — — — — — | — — — — -| — — — — — — — — — — — — — — -<br># 0 | 18 | 1.0 | [0.0, 10.0, 0.5] | 1.0 | [18.0, 1.0, 0.0, 10.0, 0.5]</pre><h4>19. How do you interpret level and logs in regressions?</h4><p>A few seemingly innocent math operations can change the interpretation of the coefficients and errors of a regression. The logarithm is one of such operations.</p><p>The logarithm may be applied at the independent and/or the dependent variables. That will determine if the regression is level-level, level-log, log-level, or log-log.</p><p><a href="https://stats.oarc.ucla.edu/other/mult-pkg/faq/general/faqhow-do-i-interpret-a-regression-model-when-some-variables-are-log-transformed/">UCLA</a> gives insight of what happens when the dependent variable is changed:</p><blockquote>when the outcome variable is log transformed, it is natural to interpret the exponentiated regression coefficients. These values correspond to changes in the ratio of the expected geometric means of the original outcome variable.</blockquote><p>So, the dependent variable interpretation becomes akin to a percentage change. If the interpretation of the dependent variable changes, a direct comparison of different regressions is comparing apples to oranges.</p><p>In order to compare different regressions, first make sure that the predicted values (or any metric derived from them) compared reflect the same units. In other words, either bring the different regression outputs to level or to log before you calculate the metrics and make comparisons.</p><h4>20. How to evaluate a regression model?</h4><p>It’s possible to build a <a href="https://api-docs.databricks.com/python/pyspark/latest/api/pyspark.ml.evaluation.RegressionEvaluator.html">RegressionEvaluator</a> object and apply it to a dataframe that contains the predictions and actual values. For example:</p><pre># dummy data<br>scoreAndLabels = [(-28.98343821, -27.0), (20.21491975, 21.5),<br>  (-25.98418959, -22.0), (30.69731842, 33.0), (74.69283752, 71.0)]<br>dataset = spark.createDataFrame(scoreAndLabels, [&quot;raw&quot;, &quot;label&quot;])<br><br># instantiate<br>evaluator = RegressionEvaluator()<br>evaluator.setPredictionCol(&quot;raw&quot;)<br><br># evaluate<br>evaluator.evaluate(dataset)<br>evaluator.evaluate(dataset, {evaluator.metricName: &quot;r2&quot;})<br>evaluator.evaluate(dataset, {evaluator.metricName: &quot;mae&quot;})</pre><p>Optionally, a weight column may be passed as a parameter.</p><h4>21. How to perform cross-validation when fitting a model?</h4><p>The <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.tuning.CrossValidator.html">CrossValidator</a> object may be used to let the model be trained with cross-validation. It receives the estimator and other parameters, and then it is used to fit the training data. This is illustrated in the example below.</p><pre># import<br>from pyspark.ml.classification import LogisticRegression<br>from pyspark.ml.evaluation import BinaryClassificationEvaluator<br>from pyspark.ml.linalg import Vectors<br>from pyspark.ml.tuning import CrossValidator, ParamGridBuilder, CrossValidatorModel<br>import tempfile<br><br># dummy data<br>dataset = spark.createDataFrame(<br>    [(Vectors.dense([0.0]), 0.0),<br>     (Vectors.dense([0.4]), 1.0),<br>     (Vectors.dense([0.5]), 0.0),<br>     (Vectors.dense([0.6]), 1.0),<br>     (Vectors.dense([1.0]), 1.0)] * 10,<br>    [&quot;features&quot;, &quot;label&quot;])<br><br># instantiate<br>lr = LogisticRegression()<br>grid = ParamGridBuilder().addGrid(lr.maxIter, [0, 1]).build()<br>evaluator = BinaryClassificationEvaluator()<br><br># instantiate<br>cv = CrossValidator(estimator=lr<br>                    , estimatorParamMaps=grid<br>                    , evaluator=evaluator<br>                    , parallelism=2)<br><br># fit<br>cvModel = cv.fit(dataset)<br>cvModel.getNumFolds()<br>cvModel.avgMetrics[0]<br><br># save<br>path = tempfile.mkdtemp()<br>model_path = path + &quot;/model&quot;<br>cvModel.write().save(model_path)<br><br># read<br>cvModelRead = CrossValidatorModel.read().load(model_path)<br>cvModelRead.avgMetrics<br><br># evaluate<br>evaluator.evaluate(cvModel.transform(dataset))<br>evaluator.evaluate(cvModelRead.transform(dataset))</pre><h4>22. How to evaluate a binary classifier?</h4><p>Binary classifiers assign True or False values (i.e. positive and negative, or two classes, hence the name <em>binary</em>). The four most important <a href="https://en.wikipedia.org/wiki/Precision_and_recall">classification metrics</a> are:</p><ul><li><strong>Accuracy</strong> measures how many values -either positive or negative- have been correctly predicted, as a percentage of the total values.</li><li><strong>Precision</strong> measures how many positive values are actually true, as a percentage of total values predicted. In a corner case, if a model only predicts one observation as positive, and it’s actually true, then precision equals 1, even if there are many false negatives.</li><li><strong>Recall</strong> measures how many positives were predicted, as a percentage of the total true values in the data. In a corner case, if a model predicts that <em>all </em>observations are positive, then recall equals 1, even if there are many false positives.</li><li><strong>F1-Score</strong> is the harmonic mean of precision and recall. It is used to balance them, and it may be adjusted with a custom weight.</li></ul><h4>23. How to orchestrate runs with MLflow?</h4><p>The basic syntax is for <a href="https://mlflow.org/docs/latest/python_api/mlflow.html">starting a run</a> is:</p><pre>import mlflow<br><br>mlflow.start_run()<br>run = mlflow.active_run()<br>print(f”Active run_id: {run.info.run_id}”)<br>mlflow.end_run()</pre><p>Using <a href="https://mlflow.org/docs/latest/python_api/mlflow.html"><em>with</em></a>, it becomes easier to call a run, and creating <a href="https://mlflow.org/docs/latest/traditional-ml/hyperparameter-tuning-with-child-runs/part1-child-runs.html">child runs</a> is done my merely adding setting <em>nested </em>to True.</p><pre>import mlflow<br><br># Create nested runs<br>with mlflow.start_run():<br>    with mlflow.start_run(nested=True) as child_run:<br>    child_run_id = child_run.info.run_id<br><br>parent_run = mlflow.get_parent_run(child_run_id)<br>print(f”child_run_id: {child_run_id}”)<br>print(f”parent_run_id: {parent_run.info.run_id}”)</pre><h3>Spark ML</h3><h4>24. What is an estimator?</h4><p><a href="https://scikit-learn.org/stable/developers/develop.html">Scikit-Learn</a> provides a fine definition of what an estimator it:</p><blockquote>an object that fits a model based on some training data and is capable of inferring some properties on new data. It can be, for instance, a classifier or a regressor. All estimators implement the fit method.</blockquote><p><a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.Estimator.html">Spark</a> has a shorter description, albeit quite similar. Estimators fit models to data.</p><p>A general example:</p><pre>estimator.fit(X, y)</pre><p>A more concrete example:</p><pre>SVC(C=100).fit(X_train, y_train)</pre><h4>25. How may scikit-learn and Spark deliver different models if the same data and parameters are used?</h4><p>The implementation of the underlying algorithms may differ, especially the methods used to reach convergence.</p><p>In Spark, <a href="https://spark.apache.org/docs/latest/mllib-optimization.html">optimization</a> is accelerated using <a href="https://spark.apache.org/docs/latest/mllib-linear-methods.html">stochastic methods</a>:</p><blockquote>linear methods use convex optimization methods to optimize the objective functions. spark.mllib uses two methods, SGD and L-BFGS, described in the optimization section. Currently, most algorithm APIs support Stochastic Gradient Descent (SGD), and a few support L-BFGS.</blockquote><p>In scikit-learn, different algorithms are used, relying on matrix inversion rather than stochastics. Plus, parallelism does not come by default, and <a href="https://scikit-learn.org/stable/computing/parallelism.html">should be configured</a> with support libraries such as <em>joblib</em>.</p><p>These underlying differences may lead to different results if your data has local optimum.</p><h4>26. What are the hardships of parallelization?</h4><p><a href="https://www.kdnuggets.com/2017/04/must-know-parallelism-algorithms.html">KDNuggets</a> highlights that:</p><blockquote>Parallelism is a good idea when the task can be divided into sub-tasks that can be executed independent of each other without communication or shared resources.</blockquote><p>However,</p><blockquote>[in] real-life, most of the programs have some sections that need to be executed in serialized fashion, and the parallelizable sub-tasks need some kind of synchronization or data transfer.</blockquote><p>In other words, parallelism becomes less relevant if tasks either (i) are built sequentially or (ii) recursively require each other’s outputs.</p><h4>27. How to optimize with Hyperopt?</h4><p>The function <a href="https://github.com/hyperopt/hyperopt/blob/master/hyperopt/fmin.py"><em>fmin</em></a><em> </em>is used to optimize a Hyperopt run.</p><p>Please notice, there is no <em>fmax</em>. If the statistical goal is to maximize a metric, then the objective function should be adapted; instead, the negative of such metric should be minimized.</p><p>The function <em>fmin</em> requires two parameters: <em>fn</em> and <em>space</em>.</p><ul><li><strong>fn</strong> is the objective function being minimzed</li><li><strong>space</strong> is the set of possible arguments that fn will take.</li></ul><p>There are a few other good-to-know optional parameters:</p><ul><li><strong>algo</strong> defines the search algorithm. The most commonly used are hyperopt.rand.suggest for Random Search and hyperopt.tpe.suggest for TPE.</li><li><strong>max_evals </strong>defines the maximum number of evaluations allowed.</li><li><strong>trials</strong> defines the storage for completed, ongoing, and scheduled evaluation points. Use <em>SparkTrials</em> for scikit-learn, and <em>Trials</em> for Hyperopt.</li></ul><p>As <a href="https://docs.databricks.com/en/machine-learning/automl-hyperparam-tuning/hyperopt-concepts.html">Databricks explains</a>:</p><blockquote>SparkTrials is designed to parallelize computations for single-machine ML models such as scikit-learn. For models created with distributed ML algorithms such as MLlib or Horovod, do not use SparkTrials. In this case the model building process is automatically parallelized on the cluster and you should use the default Hyperopt class Trials.</blockquote><p>So, the <a href="https://github.com/hyperopt/hyperopt/wiki/FMin">usage of <em>fmin</em></a> can be illustrated by:</p><pre>import pickle<br>import time<br>from hyperopt import fmin, tpe, hp, STATUS_OK<br><br>def objective(x):<br>    return {&#39;loss&#39;: x ** 2, &#39;status&#39;: STATUS_OK }<br><br>best = fmin(objective,<br>    space=hp.uniform(&#39;x&#39;, -10, 10),<br>    algo=tpe.suggest,<br>    max_evals=100)<br><br>print(best)</pre><p>Finally, Hyperopt:</p><pre>import hyperopt<br><br>best_hyperparameters = hyperopt.fmin(<br>  fn = training_function,<br>  space = search_space,<br>  algo = hyperopt.tpe.suggest,<br>  max_evals = 64,<br>  trials = hyperopt.SparkTrials())</pre><h4>28. How to convert Pandas to Spark and back?</h4><p>It is possible to actually <a href="https://docs.databricks.com/en/pandas/pyspark-pandas-conversion.html">convert</a> a Pandas DataFrame into a Spark DataFrame, and vice-versa. This is possible with <a href="https://arrow.apache.org/">Apache Arrow</a>, an in-memory columnar data format used in Apache Spark to efficiently transfer data between JVM and Python processes.</p><pre>import numpy as np<br>import pandas as pd<br><br># Enable Arrow-based columnar data transfers<br>spark.conf.set(&quot;spark.sql.execution.arrow.pyspark.enabled&quot;, &quot;true&quot;)<br><br># Generate a pandas DataFrame<br>pdf = pd.DataFrame(np.random.rand(100, 3))<br><br># Create a Spark DataFrame from a pandas DataFrame using Arrow<br>sdf = spark.createDataFrame(pdf)<br><br># Convert the Spark DataFrame back to a pandas DataFrame using Arrow<br>result_pdf = sdf.select(&quot;*&quot;).toPandas()</pre><h4>29. What is the Pandas API on Spark?</h4><p>The Pandas API on Spark is a means of using a Spark DataFrame as if it were a Pandas DataFrame. Databricks explains <a href="https://docs.databricks.com/en/pandas/pandas-on-spark.html">why and how</a>:</p><blockquote>Commonly used by data scientists, pandas is a Python package that provides easy-to-use data structures and data analysis tools for the Python programming language. However, pandas does not scale out to big data. Pandas API on Spark fills this gap by providing pandas equivalent APIs that work on Apache Spark. Pandas API on Spark is useful not only for pandas users but also PySpark users, because pandas API on Spark supports many tasks that are difficult to do with PySpark, for example plotting data directly from a PySpark DataFrame.</blockquote><p>The following method may be used to create a a pandas-on-Spark DataFrame (psdf) by passing a pandas DataFrame (pdf):</p><pre>import pyspark.pandas as ps<br><br>psdf = ps.DataFrame(pdf)<br><br># alternatively:<br>psdf = ps.from_pandas(pdf)</pre><h4>30. What is the Pandas UDF?</h4><p><a href="https://learn.microsoft.com/en-us/azure/databricks/udf/pandas">Microsoft</a> explains that:</p><blockquote>A pandas user-defined function (UDF) — also known as vectorized UDF — is a user-defined function that uses Apache Arrow to transfer data and pandas to work with the data. pandas UDFs allow vectorized operations that can increase performance up to 100x compared to row-at-a-time Python UDFs.</blockquote><p>There are four UDFs:</p><ul><li>Series to Series UDF</li><li>Iterator of Series to Iterator of Series UDF</li><li>Iterator of multiple Series to Iterator of Series UDF</li><li>Series to scalar UDF</li></ul><p><a href="https://livebook.manning.com/book/pyspark-in-action/chapter-9/1">Manning</a> provides a good decision tree to decide which UDF to use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uYNdymaD2XV_obPy.png" /></figure><h4>31. How to implement a Series to Series Pandas UDF?</h4><p>The <strong>Series to Series Pandas UDF</strong> can vectorize scalar operations with either <em>select</em> or <em>withColumn</em>. It is the most basic UDF. It is illustrated in the following snippet.</p><pre>import pandas as pd<br>from pyspark.sql.functions import col, pandas_udf<br>from pyspark.sql.types import LongType<br><br># Declare the function and create the UDF<br>def multiply_func(a: pd.Series, b: pd.Series) -&gt; pd.Series:<br>    return a * b<br><br>multiply = pandas_udf(multiply_func, returnType=LongType())<br><br># The function for a pandas_udf should be able to execute with local pandas data<br>x = pd.Series([1, 2, 3])<br>print(multiply_func(x, x))<br><br># 0    1<br># 1    4<br># 2    9<br># dtype: int64<br><br># Create a Spark DataFrame, &#39;spark&#39; is an existing SparkSession<br>df = spark.createDataFrame(pd.DataFrame(x, columns=[&quot;x&quot;]))<br><br># Execute function as a Spark vectorized UDF<br>df.select(multiply(col(&quot;x&quot;), col(&quot;x&quot;))).show()<br><br># +-------------------+<br># |multiply_func(x, x)|<br># +-------------------+<br># |                  1|<br># |                  4|<br># |                  9|<br># +-------------------+</pre><h4>32. When to use ApplyInPandas and MapInPandas?</h4><p><a href="https://learn.microsoft.com/en-us/azure/databricks/pandas/pandas-function-apis">Microsoft Documentation</a> on Databricks details that there are three types of pandas function APIs:</p><ul><li>Grouped map</li><li>Map</li><li>Cogrouped map</li></ul><p>In <strong>grouped map</strong>, <em>groupBy().applyInPandas()</em> implements a split-apply-combine pattern that will:</p><blockquote>(1) Split the data into groups by using DataFrame.groupBy.</blockquote><blockquote>(2) Apply a function on each group. The input and output of the function are both pandas.DataFrame. The input data contains all the rows and columns for each group.</blockquote><blockquote>(3) Combine the results into a new DataFrame.</blockquote><p>For example:</p><pre>df = spark.createDataFrame(<br>    [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],<br>    (&quot;id&quot;, &quot;v&quot;))<br><br>def subtract_mean(pdf):<br>    # pdf is a pandas.DataFrame<br>    v = pdf.v<br>    return pdf.assign(v=v - v.mean())<br><br>df.groupby(&quot;id&quot;)<br>  .applyInPandas(subtract_mean, schema=&quot;id long, v double&quot;)<br>  .show()<br><br># +---+----+<br># | id|   v|<br># +---+----+<br># |  1|-0.5|<br># |  1| 0.5|<br># |  2|-3.0|<br># |  2|-1.0|<br># |  2| 4.0|<br># +---+----+</pre><p>In <strong>map</strong>, <em>DataFrame.mapInPandas()</em> performs map operations transforming a pandas dataframe iterator and returns a returns the result as a PySpark DataFrame.</p><pre>df = spark.createDataFrame([(1, 21), (2, 30)], (&quot;id&quot;, &quot;age&quot;))<br><br>def filter_func(iterator):<br>    for pdf in iterator:<br>        yield pdf[pdf.id == 1]<br><br>df.mapInPandas(filter_func, schema=df.schema).show()<br># +---+---+<br># | id|age|<br># +---+---+<br># |  1| 21|<br># +---+---+</pre><p>In <strong>cogrouped map</strong>, <em>DataFrame.groupby().cogroup().applyInPandas()</em> is used to cogroup two PySpark DataFrames by a common key and then apply a Python function to each cogroup.</p><pre>import pandas as pd<br><br>df1 = spark.createDataFrame(<br>    [(20000101, 1, 1.0), (20000101, 2, 2.0), (20000102, 1, 3.0), (20000102, 2, 4.0)],<br>    (&quot;time&quot;, &quot;id&quot;, &quot;v1&quot;))<br>df2 = spark.createDataFrame(<br>    [(20000101, 1, &quot;x&quot;), (20000101, 2, &quot;y&quot;)],<br>    (&quot;time&quot;, &quot;id&quot;, &quot;v2&quot;))<br><br>def asof_join(l, r):<br>    return pd.merge_asof(l, r, on=&quot;time&quot;, by=&quot;id&quot;)<br><br>df1.groupby(&quot;id&quot;).cogroup(df2.groupby(&quot;id&quot;)).applyInPandas(<br>    asof_join, schema=&quot;time int, id int, v1 double, v2 string&quot;).show()<br><br># +--------+---+---+---+<br># |    time| id| v1| v2|<br># +--------+---+---+---+<br># |20000101|  1|1.0|  x|<br># |20000102|  1|3.0|  x|<br># |20000101|  2|2.0|  y|<br># |20000102|  2|4.0|  y|<br># +--------+---+---+---+</pre><h3>Scaling ML Models</h3><h4>33. What are ensemble methods?</h4><p>The three most famous ensemble methods are bagging, boosting, and stacking. As the name <em>ensemble</em> suggests, they try to combine multiple models to achieve a combined model that’s better performing.</p><p>These techniques may be <a href="https://towardsdatascience.com/ensemble-methods-bagging-boosting-and-stacking-c9214a10a205">described</a> as:</p><ul><li><strong>Bagging</strong> trains homogeneous weak-learners in parallel, and then combines them with some deterministic averaging process. E.g., average out different forecasts.</li><li><strong>Boosting: </strong>trains homogeneous weak-learners sequentially, and combines them following a deterministic strategy. E.g., train on the residuals of the previous model.</li><li><strong>Stacking</strong> trains heterogenous weak-learners in parallel, and then combines them by training a meta-model. E.g., train a model on top of other models.</li></ul><h4>34. What is Gradient Boosting?</h4><p>According to <a href="https://machinelearningmastery.com/gentle-introduction-gradient-boosting-algorithm-machine-learning/">Machine Learning Mastery</a>, Gradient Boosting is one of the most powerful techniques out there to build predictive models. It consists of three elements:</p><blockquote>1. A loss function to be optimized.</blockquote><blockquote>2. A weak learner to make predictions.</blockquote><blockquote>3. An additive model to add weak learners to minimize the loss function.</blockquote><p>It is possible to improve Gradient Boosting by using bagging on random forests trained with data subsamples. This more advanced technique is called <em>Stochastic Gradient Boosting</em>.</p><h3>Good luck!</h3><p>Enroll now for the Databricks <a href="https://www.databricks.com/learn/certification/machine-learning-associate">Machine Learning Associate</a> certification, and go get your badge!</p><p>Good luck on your exam!</p><p>If you found this article useful, please like, comment, share, or <a href="http://buymeacoffee.com/thecoffeeofdaniel">buy me a coffee</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49113d261ad8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>