text_plain_output_1.png image_output_1.png
from sklearn.neighbors import KNeighborsClassifier

import matplotlib.pyplot as plt

import numpy as np

import pandas as pd

import seaborn as sns

df = pd.read_csv('../input/tour-travels-customer-churn-prediction/Customertravel.csv')

df.rename(columns={'Target': 'Churn'}, inplace=True)

df.groupby('Churn').describe()

ax = sns.countplot(data=df, x='Churn')
percentage = df['Churn'].value_counts(normalize=True).values * 100
lbls = [f'{p:.1f}%' for p in percentage]

ax.bar_label(container=ax.containers[0], labels=lbls)   
plt.ylim(top=800)
plt.title('Churned (0=no, 1=yes)');  

df.isnull().sum()

df_coded = df.copy()

df_coded = df_coded.replace({'AnnualIncomeClass': {'Low Income': 0, 'Middle Income': 1, 'High Income': 2}})

dummies = ['BookedHotelOrNot', 'AccountSyncedToSocialMedia', 'FrequentFlyer']
df_coded = pd.get_dummies(df_coded, columns=dummies, drop_first=True)

df_coded.rename(columns={'BookedHotelOrNot_Yes': 'BookedHotel', 'AccountSyncedToSocialMedia_Yes': 'AccountSyncedToSocialMedia'}, inplace=True)

error_rate = []
for i in range(1, 25):
    knn = KNeighborsClassifier(n_neighbors=i)
    knn.fit(X_train, y_train)
    pred_i = knn.predict(X_test)
    error_rate.append(np.mean(pred_i != y_test))
plt.plot(range(1, 25), error_rate, color='b', linestyle='--', marker='o', markerfacecolor='r', markeredgecolor='r', markersize=8)
plt.xlabel('K')
plt.ylabel('Error Rate')
plt.title('Error Rate vs. K Value')
print('Minimum error:', np.round(min(error_rate), 3), 'at K =', error_rate.index(min(error_rate)) + 1, '\n')