Files
share/hotel_questions.ipynb
2022-01-14 10:48:45 +01:00

35 KiB

In [2]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

sns.set_style("whitegrid")

Contexte

Nous considérons un jeu de données pour expérimenter sur la prédiction des annulations de réservations de chambres d'hôtel. Nous souhaitons mesurer la qualité atteignable pour les prédictions d'annulations. Nous souhaitons également découvrir les facteurs les plus discriminants qui auront permis d'automatiser cette prédiction afin de guider la mise en œuvre de contre-mesures qui permettraient de réduire les pertes de profits liées aux annulations.

Réflexions préliminaires

Quelles sont les grandes catégories de problèmes qui peuvent être résolus par des algorithmes de machine learning ? À quelle(s) catégorie(s) pourrait appartenir le problème ci-dessus ?

Comment approcher ce problème ? Quelles peuvent être les premières étapes nécessaire pour débuter le travail de modélisation afin de bien formuler le problème ? Quelles erreurs éviter ?

In [3]:
df = pd.read_csv('https://git.sdf.org/p6e7p7/share/raw/branch/master/hotel_booking.csv')

Feature engineering

In [4]:
df.head()
Out [4]:
hotel is_canceled lead_time arrival_date_year arrival_date_month arrival_date_week_number arrival_date_day_of_month stays_in_weekend_nights stays_in_week_nights adults children babies meal country market_segment distribution_channel is_repeated_guest previous_cancellations previous_bookings_not_canceled reserved_room_type assigned_room_type booking_changes deposit_type agent company days_in_waiting_list customer_type adr required_car_parking_spaces total_of_special_requests reservation_status reservation_status_date
0 Resort Hotel 0 342 2015 July 27 1 0 0 2 0.0 0 BB PRT Direct Direct 0 0 0 C C 3 No Deposit NaN NaN 0 Transient 0.0 0 0 Check-Out 2015-07-01
1 Resort Hotel 0 737 2015 July 27 1 0 0 2 0.0 0 BB PRT Direct Direct 0 0 0 C C 4 No Deposit NaN NaN 0 Transient 0.0 0 0 Check-Out 2015-07-01
2 Resort Hotel 0 7 2015 July 27 1 0 1 1 0.0 0 BB GBR Direct Direct 0 0 0 A C 0 No Deposit NaN NaN 0 Transient 75.0 0 0 Check-Out 2015-07-02
3 Resort Hotel 0 13 2015 July 27 1 0 1 1 0.0 0 BB GBR Corporate Corporate 0 0 0 A A 0 No Deposit 304.0 NaN 0 Transient 75.0 0 0 Check-Out 2015-07-02
4 Resort Hotel 0 14 2015 July 27 1 0 2 2 0.0 0 BB GBR Online TA TA/TO 0 0 0 A A 0 No Deposit 240.0 NaN 0 Transient 98.0 0 1 Check-Out 2015-07-03
In [5]:
df.columns
Out [5]:
Index(['hotel', 'is_canceled', 'lead_time', 'arrival_date_year',
       'arrival_date_month', 'arrival_date_week_number',
       'arrival_date_day_of_month', 'stays_in_weekend_nights',
       'stays_in_week_nights', 'adults', 'children', 'babies', 'meal',
       'country', 'market_segment', 'distribution_channel',
       'is_repeated_guest', 'previous_cancellations',
       'previous_bookings_not_canceled', 'reserved_room_type',
       'assigned_room_type', 'booking_changes', 'deposit_type', 'agent',
       'company', 'days_in_waiting_list', 'customer_type', 'adr',
       'required_car_parking_spaces', 'total_of_special_requests',
       'reservation_status', 'reservation_status_date'],
      dtype='object')
variable class description
hotel character Hotel (H1 = Resort Hotel or H2 = City Hotel)
is_canceled double Value indicating if the booking was canceled (1) or not (0)
lead_time double Number of days that elapsed between the entering date of the booking into the PMS and the arrival date
arrival_date_year double Year of arrival date
arrival_date_month character Month of arrival date
arrival_date_week_number double Week number of year for arrival date
arrival_date_day_of_month double Day of arrival date
stays_in_weekend_nights double Number of weekend nights (Saturday or Sunday) the guest stayed or booked to stay at the hotel
stays_in_week_nights double Number of week nights (Monday to Friday) the guest stayed or booked to stay at the hotel
adults double Number of adults
children double Number of children
babies double Number of babies
meal character Type of meal booked. Categories are presented in standard hospitality meal packages:
Undefined/SC – no meal package;
BB – Bed & Breakfast;
HB – Half board (breakfast and one other meal – usually dinner);
FB – Full board (breakfast, lunch and dinner)
country character Country of origin. Categories are represented in the ISO 3155–3:2013 format
market_segment character Market segment designation. In categories, the term “TA” means “Travel Agents” and “TO” means “Tour Operators”
distribution_channel character Booking distribution channel. The term “TA” means “Travel Agents” and “TO” means “Tour Operators”
is_repeated_guest double Value indicating if the booking name was from a repeated guest (1) or not (0)
previous_cancellations double Number of previous bookings that were cancelled by the customer prior to the current booking
previous_bookings_not_canceled double Number of previous bookings not cancelled by the customer prior to the current booking
reserved_room_type character Code of room type reserved. Code is presented instead of designation for anonymity reasons
assigned_room_type character Code for the type of room assigned to the booking. Sometimes the assigned room type differs from the reserved room type due to hotel operation reasons (e.g. overbooking) or by customer request. Code is presented instead of designation for anonymity reasons
booking_changes double Number of changes/amendments made to the booking from the moment the booking was entered on the PMS until the moment of check-in or cancellation
deposit_type character Indication on if the customer made a deposit to guarantee the booking. This variable can assume three categories:
No Deposit – no deposit was made;
Non Refund – a deposit was made in the value of the total stay cost;
Refundable – a deposit was made with a value under the total cost of stay.
agent character ID of the travel agency that made the booking
company character ID of the company/entity that made the booking or responsible for paying the booking. ID is presented instead of designation for anonymity reasons
days_in_waiting_list double Number of days the booking was in the waiting list before it was confirmed to the customer
customer_type character Type of booking, assuming one of four categories:
Contract - when the booking has an allotment or other type of contract associated to it;
Group – when the booking is associated to a group;
Transient – when the booking is not part of a group or contract, and is not associated to other transient booking;
Transient-party – when the booking is transient, but is associated to at least other transient booking
adr double Average Daily Rate as defined by dividing the sum of all lodging transactions by the total number of staying nights
required_car_parking_spaces double Number of car parking spaces required by the customer
total_of_special_requests double Number of special requests made by the customer (e.g. twin bed or high floor)
reservation_status character Reservation last status, assuming one of three categories:
Canceled – booking was canceled by the customer;
Check-Out – customer has checked in but already departed;
No-Show – customer did not check-in and did inform the hotel of the reason why
reservation_status_date double Date at which the last status was set. This variable can be used in conjunction with the ReservationStatus to understand when was the booking canceled or when did the customer checked-out of the hotel
In [6]:
df.dtypes
Out [6]:
hotel                              object
is_canceled                         int64
lead_time                           int64
arrival_date_year                   int64
arrival_date_month                 object
arrival_date_week_number            int64
arrival_date_day_of_month           int64
stays_in_weekend_nights             int64
stays_in_week_nights                int64
adults                              int64
children                          float64
babies                              int64
meal                               object
country                            object
market_segment                     object
distribution_channel               object
is_repeated_guest                   int64
previous_cancellations              int64
previous_bookings_not_canceled      int64
reserved_room_type                 object
assigned_room_type                 object
booking_changes                     int64
deposit_type                       object
agent                             float64
company                           float64
days_in_waiting_list                int64
customer_type                      object
adr                               float64
required_car_parking_spaces         int64
total_of_special_requests           int64
reservation_status                 object
reservation_status_date            object
dtype: object
In [7]:
df.shape
Out [7]:
(119390, 32)

Introduction de variables calculées

Introduire de nouvelles variables qui sont des transformations de variables existantes.

  • guests est la somme de adults, children et babies
  • different_room_assigned doit indiquer si reserved_room_type et assigned_room_type diffèrent.

Supprimer les variables adults, children, babies, reserved_room_type et assigned_room_type.

In [7]:

Gestion des valeurs manquantes et sélection de variables

Compter les valeurs manquantes pour chaque variable.

In [7]:

Combien de valeurs distinctes possèdent les variables agent et company ? Comment se répartissent ces valeurs en fréquence ?

In [7]:

Comment se répartissent les valeurs distinctes de la variable country?

In [7]:

En analysant le processus métier, nous apprenons que le pays d'origine des clients est par défaut le Portugal. Il est éventuellement mis à jour au moment du check-in.

Étant donnée cette information, que pouvons-nous faire avec la variable country?

In [7]:

Remplacer les valeurs manquantes de guests par la valeur la plus fréquente que prend cette variable.

In [ ]:

Observer la répartition des catégories de la variable distribution_channel en fonction des catégories de la variable market_segment.

Par exemple, nous souhaitons découvrir que la catégorie Corporate de la variable distribution_channel se distribue à 72% dans la catégorie Corporate, 18% dans la catégorie Groups... de la variable market_segment.

In [7]:

Étant donné ce fort recouvrement, nous choisissons de retirer la variable distribution_channel.

In [7]:

Dans le cadre de cet exemple, nous proposons de supprimer également les variables reservation_status, reservation_status_date.

In [7]:

Par ailleurs, au moment de la collecte du jeu de données, les réservations dont la date de check-in est dans le futur ont un statut qui est soit inconnu, soit annulé. Les réservations dont le statut est pour l'instant inconnu pourraient être finalement annulées. Ainsi, pour ne pas introduire un biais artificiel lors de la construction d'un algorithme prédictif, pour les réservations dont la date d'enregistrement est future, il a été décidé de ne conserver que celles dont le statut est déjà "annulé". Quel impact cette décision peut-elle avoir sur les variables temporelles : arrival_date_year, arrival_date_month, arrival_date_week_number et arrival_date_day_of_month ?

In [7]:

Visualisations pour explorer le jeu de données

Tracer un histogramme de la variable lead_time.

In [7]:

Discrétiser la variable lead_time en intervalles : (0,100], (100,200], (200,300], (300,400], (400,500] et (500, 800] pour ensuite tracer un diagramme en bâtons avec sur l'axe des abscisses ces nouvelles catégories et sur l'axe des y les proportions d'annulations pour chacun des deux hôtels.

In [7]:
In [ ]:
df = df.drop(['cat_lead_time'], axis=1)

Construction d'un modèle prédictif

Construire un modèle prédictif basé sur l'algorithme de la forêt aléatoire (Random Forest).

Encodage des variables catégorielles

Transformer les colonnes qui correspondent à des catégories représentées par des chaînes de caractères en variables one-hot encodées.

In [7]:

Échantillonage du jeu de données

Découper le jeu de données en une dataframe X qui ne contient pas la variable à prédire (is_canceled) et une série y constituée de la variable à prédire.

In [7]:

Séparer ensuite le jeu de données en une partie pour l'apprentissage (70%) et une partie pour le test (30%). Pourquoi est-ce nécessaire ?

In [7]:

Apprentissage du modèle

Construire un modèle de forêt aléatoire en conservant les valeurs par défaut de tous les hyperparamètres. Qu'est-ce qu'un hyperparamètre ?

In [7]:

Évaluation du modèle

Quelle est la matrice de confusion de ce modèle sur le jeu de test ?

In [7]:

Quels sont la précision et le rappel de ce modèle sur le jeu de test ?

In [7]:

Afficher la courbe précision/rappel associée à ce modèle prédictif.

In [7]:

Optimisation des hyperparamètres

Tester par grid search avec validation croisée multi-plis quelques possibilités de valeurs d'hyperparamètres du modèle de forêt aléatoire. Conserver les meilleures valeurs et ré-entrainer le modèle sur tout le jeu d'entraînement. Vérifier sa performance sur le jeu de test.

In [7]:

Importance des variables prédictives

Analyser l'importance relative des différentes variables prédictives selon le modèle de forêt aléatoire.

In [7]: