Machine Learning with PySpark ML | Case Study

In Machine Learning with PySpark ML we took a theoretical look at what PySpark ML is, what its fundamental concepts are, and how to structure a machine learning process using estimators, transformers, models, and pipelines. In this second part, we’ll focus on how to apply these concepts to a real-world scenario by building a complete training and prediction workflow that will allow us to gain an in-depth understanding of all the stages involved in the process.

To do this, we’ll use a simple dataset and work our way through the different main stages of the entire process. The main goal isn’t to obtain the most accurate model possible, nor to demonstrate PySpark’s power in processing massive amounts of data. Rather, it’s to understand how the different pieces fit together to create a process that we can run as many times as we want.

Machine Learning use case with PySpark

First, we need to define the objective we want to achieve in this process. In this case, our goal will be to build a model capable of predicting whether a hotel reservation will be canceled based on the available information about it.

To do this, we’ll use the Hotel Booking Demand dataset available on Kaggle. This dataset contains information about reservations made at two types of establishments: a city hotel and a vacation hotel. Each row represents a reservation and includes variables related to the characteristics of the stay, the customer, the sales channel, and the reservation history.

The variable we want to predict is is_canceled, which can take two possible values. Therefore, we are dealing with a binary classification problem.

  • 0 if the reservation was not canceled
  • 1 if the reservation was canceled

To train the model, we will use only information that may be available before the final outcome of the reservation is known. This is especially important because some variables in the dataset contain information generated after the reservation has already been canceled or completed. Using those variables would introduce data leakage, resulting in a model with artificially good results.

At this point, it’s important to clarify something. As we’ve mentioned, the goal of this article isn’t to find the model with the highest possible accuracy. The purpose is to use a real-world case to walk through the different stages of a machine learning workflow with PySpark ML.

PySpark metrics used

As the primary metric, we’ll use the recall for canceled reservations, which will allow us to measure what percentage of actual cancellations the model is able to identify. As a supplementary metric, we’ll use ROC-AUC to gain a broader view of the model’s ability to distinguish between canceled and non-canceled reservations.

Now that we have a clear understanding of what we’re dealing with and the goal we want to achieve, the next step is to load the data and perform an initial EDA to analyse the problem at hand.

Loading and basic data exploration

Once the problem has been defined, the next step is to load the dataset and perform an initial exploration to help us understand the data structure before we even begin preparing the variables.

To do this, we’ll first download the dataset and load the CSV file using Spark.

Screenshot of a CSV file being loaded using Spark

The header=True option indicates that the first row of the file contains the column names. Meanwhile, inferSchema=True allows Spark to automatically attempt to identify the type of each column.

Once the dataset has been loaded, we proceed to check the number of records and columns available. To do this, we will use the following commands.

Screenshot showing how to check the number of available records and columns using Spark

In addition, it’s also a good idea to review the schema that Spark has identified to make sure it’s correct.

Screenshot of the dataset schema review using Spark

Distribution of the target variable

Another important point is to check the distribution of our target variable, which, as we have mentioned, is is_canceled in this case. Therefore, we will use the following command in PySpark.

Screenshot of the target variable review using Spark

This allows us to determine how many reservations belong to each class and to check whether there is a significant imbalance between them. In this case, approximately 63% of the reservations were not canceled, compared to 37% that were.

It is important to review this distribution before training the model. This is because when one class is much more prevalent than the other, the model may favor the class with the higher percentage, which can affect both the training process and the interpretation of the results.

Finally, we will perform a basic check for null values to ensure that no fields are affected by them.

Screenshot of checking for null values using Spark

The purpose of all these checks is not to conduct an in-depth analysis of the dataset, but rather to identify basic issues related to structure, data types, and null values before selecting and transforming the variables that the model will use. So, once we’ve reviewed the dataset, let’s move on to the next step.

Data preparation

Now that we’ve explored the dataset, the next step is to select and prepare the variables that the model will use in PySpark. To do this, we won’t use all the available columns; instead, we’ll select the ones that interest us, since the goal is to work with a representative set of numerical and categorical variables while keeping the dataset as simple as possible.

Additionally, before selecting the variables, we must analyze potential data leakage—that is, information that won’t be available at the actual time the prediction is made.

In this dataset, there are some columns that contain information about the final outcome of the reservation. For example:

  • reservation_status 
  • reservation_status_date

These variables indicate whether a reservation ended as canceled, completed, or a no-show. Therefore, using them to predict the is_canceled field would introduce information about the future and produce artificially good metrics. For this reason, we will remove these columns from the model.

We will also exclude some variables whose values may change over the course of the reservation, such as assigned_room_type or booking_changes. In this case, we’ll assume that we want to make the prediction early in the booking process, using only information that would be available at that time.

Variable selection and definition

For the model, we’ll use the following categorical and numerical variables and define the target variable. Then, only these columns will be selected:

Screenshot showing the selection of specific columns from the dataset using Spark

The next step is to ensure that all numeric variables are actually of a numeric type. Although we used inferSchema=True when loading the CSV, this does not guarantee that Spark will always interpret all columns as expected. If a column ends up being interpreted as a string, VectorAssembler will not be able to use it later.

Therefore, we explicitly convert the numeric variables to double while performing some basic data cleaning. For example, we replace null values in the children column with 0, replace any null values in categorical variables with a generic category, and remove records that are inconsistent with our use case (such as reservations with no guests or a negative adr value).

Screenshot showing the conversion of numeric variables to `double` using Spark

Before continuing, we can verify that the selected variables do not contain null values.

Screenshot showing that there are no null values in the selected variables using Spark

Now that we’ve verified this, we can confirm that the data is ready to be split into training and test sets. However, we still can’t transform the categorical variables or create the features column, since those transformations will be included later in the pipeline.

Splitting into train and test in PySpark

Once the data is ready, the next step is to split the dataset into two independent sets: one for training the model and the other for validating its performance using data it hasn’t seen during training.

To do this, we’ll use 80% of the reservations for training and the remaining 20% for testing.

Screenshot showing the split of the dataset into train and test sets using Spark

The seed seed=42 allows us to reproduce the same partitioning in future runs. If we didn’t specify a fixed seed, Spark might assign different records to each partition each time we ran the notebook.

Once this step is complete, we can check how many records remain in each partition.

Screenshot showing the number of records in the train and test datasets using Spark

This split is done to avoid evaluating the model using the same observations used to train it. If we did that, the metrics obtained would show how well the model fits the known data, but not its true ability to generalise to new records. So this is why the entire learning process will be carried out solely on train_df, reserving test_df for the evaluation phase.

Furthermore, once the split has been made, it is important to verify that the distribution of the target variable remains reasonably similar across both datasets.

Screenshot showing the distribution of the target variable in the train and test datasets using Spark

In this example, to keep things simple, we’ll use a random split. However, in a real-world scenario, it might be more appropriate to use a temporal split—training on older reserves and evaluating on more recent ones—since that’s how the model would operate in a production environment.

Building the pipeline

Once the training and test data have been separated, we can build the pipeline that will apply all the necessary transformations before training the model.

In PySpark ML, algorithms do not work directly with categorical columns in text format, nor with multiple independent columns. The model expects to receive a single vector column, typically called features. For this reason, the pipeline will perform four steps:

  1. Convert categorical text variables to numerical indices using StringIndexer.
  2. Transform those indices into binary variables using OneHotEncoder.
  3. Combine all the transformed numerical and categorical variables into a single features column using VectorAssembler.
  4. Train a logistic regression model on that feature vector.

Next, we’ll carry out the process. First, let’s generate the names of the intermediate columns that StringIndexer and OneHotEncoder will use:

Screenshot showing the generation of the intermediate column names that will be used by StringIndexer and OneHotEncoder using Spark

Next, we use StringIndexer to convert text categories into numerical indices. This way, variables such as hotel, city hotel, or resort hotel can be internally converted to values such as 0.0 or 1.0.

Screenshot showing the conversion of text categories into numerical indexes using Spark

The parameter handleInvalid = ‘keep’ allows Spark to treat a category that appears during prediction but was not present during training as an additional category, rather than generating an error.

However, these indices should not be fed directly into the model. A value of 1 does not necessarily mean that a category is greater than or more important than category 0. To solve this problem, we will apply a OneHotEncoder.

Screenshot of a transformation using OneHotEncoder with Spark

This transformation represents each category using a binary vector, thereby avoiding the introduction of an artificial relationship between categories.

Next, we combine the original numerical variables and the coded categorical variables into a single column.

Screenshot showing the combination of the original numerical variables and the coded categorical variables in a single column using Spark

The result will be a features column containing all the information the model will use to make the prediction.

Classifier with logistic regression

Finally, we define the classifier. For this example, we will use logistic regression:

Screenshot of the definition of the logistic regression classifier using Spark

Logistic regression is a good choice in this case because it allows us to solve a binary classification problem easily and, in addition to generating a prediction, provides an estimated probability of cancellation.

Once all the stages have been defined, we group them into a single pipeline.

Screenshot showing all the stages defined within a single pipeline grouped together using Spark

The main advantage of this step is that the transformations will be learned using only the training data and will then be applied in exactly the same way to the test data or to new reserves. This will allow us to avoid inconsistencies between the training and prediction processes.

Training the model in PySpark

Now that we’ve built the pipeline, the next step is to train it using only the training dataset. To do this, we’ll use PySpark’s fit() method:

Screenshot of model training using the “train” dataset with Spark

When we run fit(), Spark goes through the different stages of the pipeline and trains the ones that need to learn from the data.

In our case:

  • StringIndexer learns which categories exist in each variable and which index to assign to each one.
  • OneHotEncoder learns how to represent those categories using vectors.
  • VectorAssembler simply combines the variables, so it does not need to learn any parameters.
  • LogisticRegression learns the coefficients that relate the characteristics of each reservation to the probability of cancellation.

The pipeline object we created in the previous step was merely the definition of the process. After running fit(), we obtain a PipelineModel, which contains all the transformations and parameters that have already been trained:

Screenshot of the PipelineModel obtained with all transformations and parameters already trained using Spark

The difference between these two concepts is important:

  • A Pipeline defines the stages we want to run.
  • A PipelineModel contains those stages once they have been trained.

Now that we have the PipelineModel, we can check which stages are part of the trained model.

Screenshot showing which stages are part of the model trained using Spark

At this point, we already have a fully trained model that is ready to process data it has not seen before. So the next step will be to apply it to test_df to generate predictions and evaluate its performance.

Prediction and evaluation

We’ve already defined and trained the pipeline, so now we can apply it to the test dataset to generate predictions for reservations that the model did not use during training. To do this, we’ll use PySpark’s transform() method.

Screenshot showing how to make predictions using the model pipeline with Spark

When you call transform(), Spark automatically runs through all the stages of the PipelineModel, transforms the categorical variables, builds the features column, and applies the logistic regression model. Once this process is complete, the result will include, in addition to the original columns, several new columns named rawPrediction, probability, and prediction.

For this example, the most useful column is probability, which contains the estimated probability for each of the two classes.

We can directly extract the probability of cancellation corresponding to class 1.

Screenshot of the cancellation probability obtained from predictions using Spark

Now, we can view some predictions along with relevant information for each reservation:

Screenshot showing some predictions using Spark

The is_canceled column represents the actual outcome. The prediction column contains the model’s prediction, where 0.0 indicates a prediction of no cancellation and 1.0 indicates a prediction of cancellation.

Model performance

Now that we have the results, the next step is to evaluate the model’s performance. To do this, we’ll use recall for canceled reservations as our primary metric, which tells us what percentage of reservations that were actually canceled the model was able to correctly identify. Additionally, we’ll use ROC-AUC, which allows us to measure the model’s overall ability to distinguish between canceled and non-canceled reservations.

To do this, we can calculate these metrics using MulticlassClassificationEvaluator and BinaryClassificationEvaluator.

Screenshot of the model performance evaluation using Spark

For example, a recall of 0.8 would indicate that the model is able to detect approximately 80% of the reservations that are ultimately canceled.

The ROC-AUC, on the other hand, takes values between 0 and 1. The closer it is to 1, the greater the model’s ability to correctly distinguish between canceled and non-canceled reservations.

In our case, we obtain a recall of 0.5939. This result means that the model correctly identifies approximately 59.4% of the reservations that are ultimately canceled.

On the other hand, we obtain an ROC-AUC of 0.8482, which indicates that the model has a good overall ability to distinguish between canceled and non-canceled reservations.

The difference between these two metrics is important. Although the model separates the two classes quite well, with the default classification threshold, it still fails to detect a significant portion of actual cancellations. In a real-world scenario, we could adjust that threshold to increase recall, although this would typically come at the cost of generating more false positives.

Confusion matrix

Finally, we can construct a confusion matrix, which will allow us to distinguish between four scenarios:

  • True Negative. Bookings are not canceled, and the model predicts that they will not be canceled.
  • False Positive. No cancellations occur, but the model predicts a cancellation.
  • False Negative. Bookings are canceled, but the model predicts that they will not be canceled.
  • True Positive. The reservation is canceled, and the model predicts a cancellation.

In our case using PySpark, false negatives are of particular interest because they represent reservations that were ultimately canceled but that the model failed to detect.

Screenshot of the model performance evaluation using a confusion matrix with Spark

Or, to put it another way so that it’s easier to understand, it would look like this:

Screenshot showing the false positives, true positives, and true negatives obtained using Spark

These metrics should be interpreted together. A model may increase recall by detecting more cancellations, but in turn generate more false positives. Therefore, the evaluation should not focus solely on looking at a single figure, but rather on understanding what kinds of errors the model is making and what their impact would be in the hotel industry.

Predicting new data with PySpark

Once the model has been trained and evaluated, the final step is to use it to generate predictions for new reservations. This part is especially important because it shows how the model would actually be used once trained.

Thanks to the PipelineModel, we don’t need to manually repeat any of the transformations performed during training. We simply need to feed it new reservations with the same input structure and run PySpark’s transform() method.

To test this, let’s create three fictitious reservations.

Screenshot of predictions based on new data using Spark

As you can see, we did not include the is_canceled variable in these new observations, since that is precisely the value we want to predict.

Now that we have created the DataFrame, we can apply the trained model directly to it. This way, PipelineModel will handle the same transformations used during training.

Screenshot of the application applying the pre-trained model to new data using Spark

Now, we can display only the information needed to interpret the result.

Screenshot of the results from applying the pre-trained model to new data using Spark

The cancellation_probability column shows the estimated probability that each reservation will ultimately be canceled. Meanwhile, the prediction column represents the model’s final classification.

As you can see, by using pipelines, the same trained model can receive new observations and automatically apply all necessary preprocessing before making a prediction. This ensures a consistent workflow between training and using the model.

Conclusion

Thanks to this article, we now have a much more comprehensive understanding of how PySpark ML works and how to use it.

In the first part, we looked at the theoretical structure of a machine learning process in PySpark ML, reviewing concepts such as transformers, estimators, models, features, labels, and pipelines. In this second instalment, we’ve put these concepts into practice through a complete case study on predicting hotel cancellations—from data preparation to training, evaluation, and prediction for new reservations.

That’s it for today’s post. If you found it interesting, we encourage you to visit the Data Science category to see all the related posts and to share it in networks with your contacts. See you soon!

Luís Galdeano
Luís Galdeano
Articles: 18