<jupyter_start><jupyter_text>ANALISIS DATA PEMBOKINGAN HOTEL![title](FIND_IT_2020.png) source : FIND IT 2020 DATA ANALYST oleh :    <NAME> (Telkom University)    <NAME> (Telkom University)  LIBRARYModule library yang akan digunakan Modul yang digunakan sebagai berikut :- Pandas- matplotlib- Seaborn- Numpy- sklearn (scikit-learn)<jupyter_code>import timeit
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from sklearn.feature_selection import RFE
from sklearn.preprocessing import LabelEncoder
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.metrics import classification_report as report<jupyter_output><empty_output><jupyter_text>LOAD DATA FILEload file 'hotel_bookings.csv' kedalam notebook<jupyter_code>df = pd.read_csv('hotel_bookings.csv',parse_dates=True)
df.head()<jupyter_output><empty_output><jupyter_text>EDA (Exploratory Data Analysis)explorasi informasi-informasi atau kesimpualan yang terkait dengan data ini.<jupyter_code>df.info()<jupyter_output><class 'pandas.core.frame.DataFrame'>
RangeIndex: 119390 entries, 0 to 119389
Data columns (total 32 columns):
 #   Column                          Non-Null Count   Dtype  
---  ------                          --------------   -----  
 0   hotel                           119390 non-null  object 
 1   is_canceled                     119390 non-null  int64  
 2   lead_time                       119390 non-null  int64  
 3   arrival_date_year               119390 non-null  int64  
 4   arrival_date_month              119390 non-null  object 
 5   arrival_date_week_number        119390 non-null  int64  
 6   arrival_date_day_of_month       119390 non-null  int64  
 7   stays_in_weekend_nights         119390 non-null  int64  
 8   stays_in_week_nights            119390 non-null  int64  
 9   adults                          119390 non-null  int64  
 10  children                        119386 non-null  float64
 11  babies                          119390 non-null  int64  
 12  meal            [...]<jupyter_text>jadi pada data tersebut diperoleh informasi sebagai berikut.* total data 119.389 dengan total 31 column* memory yang digunakan kurang lebih 29.1 MB* data yang kosong berapa pada column children, country dan company<jupyter_code>df.describe()<jupyter_output><empty_output><jupyter_text>Perlu cleaning data untuk dapat summary yang tepat   1. Cleaning Datamembenahi data-data yang dapat menggangu pada pengambilan kesimpulan<jupyter_code>#df.hotel.astype('category')
# df['reservation_status_date'] = pd.to_datetime(df['reservation_status_date'])
# df = df.set_index(['reservation_status_date']).sort_index()
df.head()
for column in df.columns:
    print(f'total unique value dari column "{column}"')
    print(df[column].value_counts())
    print()
df.isna().sum()/len(df)
df = df.drop(['agent','company'],axis=1)
df = df.ffill()
df.isna().sum()/len(df)
df_new = df
df_new['hotel'] = df_new['hotel'].astype('category')
df_new['arrival_date_month'] = df_new['arrival_date_month'].astype('category') 
df_new['meal'] = df_new['meal'].astype('category')
df_new['market_segment'] = df_new['market_segment'].astype('category')
df_new['distribution_channel'] = df_new['distribution_channel'].astype('category')
df_new['reserved_room_type'] = df_new['reserved_room_type'].astype('category')
df_new['assigned_room_type'] = df_new['assigned_room_type'].astype('category')
df_new['deposit_type'] = df_new['deposit_type'].astype('category')
df_new['customer_type'] = df_new['customer_type'].astype('category')
df_new['reservation_status'] = df_new['reservation_status'].astype('category')
df_new['is_canceled'] = df_new['is_canceled'].astype('category')
df_new['country'] = df_new['country'].astype('category')
df_new.info()<jupyter_output><class 'pandas.core.frame.DataFrame'>
RangeIndex: 119390 entries, 0 to 119389
Data columns (total 30 columns):
 #   Column                          Non-Null Count   Dtype   
---  ------                          --------------   -----   
 0   hotel                           119390 non-null  category
 1   is_canceled                     119390 non-null  category
 2   lead_time                       119390 non-null  int64   
 3   arrival_date_year               119390 non-null  int64   
 4   arrival_date_month              119390 non-null  category
 5   arrival_date_week_number        119390 non-null  int64   
 6   arrival_date_day_of_month       119390 non-null  int64   
 7   stays_in_weekend_nights         119390 non-null  int64   
 8   stays_in_week_nights            119390 non-null  int64   
 9   adults                          119390 non-null  int64   
 10  children                        119390 non-null  float64 
 11  babies                          119390 non-null  int64   
 12  me[...]<jupyter_text>2. Visualisasi Datarepresentasi data-data untuk membantu dalam mendapatkan kesimplan yang tepat<jupyter_code>print(df.groupby('hotel')['is_canceled'].value_counts())
sns.set_palette('coolwarm')
plot = sns.countplot(x='hotel',data=df,hue='is_canceled')
plt.title('Jumlah Pembatalan pembokingan berdasarkan jenis hotel')
plt.yticks([0,10_000,20_000,30_000,40_000],[0,'10K','20K','30K','40K'])
plt.legend(title='Pembatalan')
plt.xlabel('')
plt.ylabel(' jumlah')
plt.show()<jupyter_output>hotel         is_canceled
City Hotel    0              46228
              1              33102
Resort Hotel  0              28938
              1              11122
Name: is_canceled, dtype: int64<jupyter_text>Dari grafik diatas, kita mengetahui bahwa Pesanan pada city hotel banyak yang dibatalkan ketimbang resort hotel<jupyter_code>sns.set()
corr = df_new.corr()
mask = np.triu(np.ones_like(corr,dtype=bool))
sns.heatmap(corr,mask=mask,center=0,linewidth=1,cmap='Blues')
plt.title('Korelasi Antar Feature')
plt.show()<jupyter_output><empty_output><jupyter_text>berdasarkan hasil analisis data diatas, kami mencari korelasi antara feature yang ada guna mereduksi banyak feature yang akan digunakan dalam proses pembuatan model:feature stay_in_week_nights dan stay_in_weekend_nights memiliki korelasi yang cukup tinggi, sehingga apabila kita membuang salah satunya informasi yang didapatkan tetap utuhfeature previous_booking_not_canceled dan is_repeated_guest juga memiliki korelasi yang cukup tinggi kedua setelah feature stay_in_week_nights.Berdasarkan data-data yang diperoleh, maka kami menarik kesimpulan sebagai berikut:* feature stay_in_week_nights akan di drop dikarenakan dapat digantikan dengan stay_in_weekend_nights, alasannya karena dalam reservasi pembokingan hotel, dalam kenyataanya adalah saat liburan(weekend) akan sangat berpengaruh dibandingkan dengan pembokingan biasa pada hari libur (sabtu/minggu)* feature previous_booking_not_canceled akan di drop dikarenakan, jika is_repeated_guest / tamu yang sudah pernah menginap, kemungkinan besar tidak membatalkan sebelumnya.<jupyter_code>df_new = df_new.drop(['stays_in_week_nights','previous_bookings_not_canceled'],axis=1)
df_new.info()
df_new.reset_index()
X,y = df_new.drop(['is_canceled','reservation_status_date'],axis=1) , df_new['is_canceled']<jupyter_output><empty_output><jupyter_text>TRAIN MODEL<jupyter_code>encoder = LabelEncoder()
X['hotel'] = encoder.fit_transform(df['hotel'])
X['arrival_date_month'] = encoder.fit_transform(df['hotel'])
X['meal'] = encoder.fit_transform(df['meal'])
X['market_segment'] = encoder.fit_transform(df['market_segment'])
X['distribution_channel'] = encoder.fit_transform(df['distribution_channel'])
X['reserved_room_type'] = encoder.fit_transform(df['reserved_room_type'])
X['assigned_room_type'] = encoder.fit_transform(df['assigned_room_type'])
X['deposit_type'] = encoder.fit_transform(df['deposit_type'])
X['customer_type'] = encoder.fit_transform(df['customer_type'])
X['reservation_status'] = encoder.fit_transform(df['reservation_status'])
X['country'] = encoder.fit_transform(df['country'])
rfe = RFE(RandomForestClassifier(),10,step=1,verbose=0)
%timeit rfe.fit(X,y)
mask = rfe.support_
X_new = X.loc[:,mask]
print(X_new.columns)
X_train,X_test,y_train,y_test = train_test_split(X_new,y,stratify=y,test_size=0.25,random_state=46)
rf = RandomForestClassifier(n_jobs=-1,max_features=10)
%timeit rf.fit(X_train,y_train)
rf.score(X_test,y_test)
acc = rf.score(X_test,y_test)

print(f'Akurasi model prediksi pembatalan booking hotel sebesar\t:  {acc*100}%')

cv = cross_val_score(rf,X_train,y_train,cv=10)
cv.mean()

print(report(y_test,rf.predict(X_test)))
df.head()
X_new.head()
df.head()
predict = rf.predict(X_new)

final = pd.DataFrame()
final['hotel'] = df_new['hotel']
final['is_canceled'] = df_new['is_canceled']
final['predict_is_canceled'] = predict
final.head(20)
final.to_excel('analyst.xlsx')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10877390326209224, 'fraction_numerical': 0.03880764904386952, 'mean_word_length': 4.292261904761904, 'pattern_counts': {'":': 0, '<': 38, '<?xml version=': 0, '>': 38, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '631249', 'license': 'MIT', 'n_tokens_mistral': 3399, 'n_tokens_neox': 3081, 'n_words': 610, 'path': 'analyst.ipynb', 'repo_name': 'cahyoardhi/ugm-find-it-data-analytic', 'size': '8922'}