application_vnd.jupyter.stderr_output_2.png application_vnd.jupyter.stderr_output_1.png
from datetime import datetime

from sklearn import preprocessing

from sklearn.metrics import accuracy_score

from sklearn.model_selection import train_test_split

from sklearn.neighbors import KNeighborsClassifier

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

name = 'Raghu'
from datetime import datetime
started_at = datetime.now().strftime('%H:%M:%S')
train_data = pd.read_csv('/kaggle/input/titanic/train.csv')
test_data = pd.read_csv('/kaggle/input/titanic/test.csv')

def massage_data(data):
    data['Honorific'] = data['Name']
    titles = data['Name'].str.split(',')
    for indx, title in enumerate(titles):
        data['Honorific'][indx] = title[1].split('.')[0]
    data['HonorificEnc'] = data['Honorific']
    for indx, hon in enumerate(train_data.Honorific.value_counts().index):
        data.HonorificEnc.replace(hon, indx, inplace=True)
    data['CoPassengers'] = data['SibSp'] + data['Parch']
    data.Sex.replace('male', 0, inplace=True)
    data.Sex.replace('female', 1, inplace=True)
    most_likely_fare = data['Fare'].mean()
    data['Fare'] = data['Fare'].fillna(most_likely_fare)
    most_likely_age = data['Age'].mean()
    data['Age'] = data['Age'].fillna(most_likely_age)
    most_likely_embarkation = data['Embarked'].mode()
    data['Embarked'] = data['Embarked'].fillna(most_likely_embarkation)
    data['EmbarkedEnc'] = data['Embarked']
    data.EmbarkedEnc.replace('S', 0, inplace=True)
    data.EmbarkedEnc.replace('C', 1, inplace=True)
    data.EmbarkedEnc.replace('Q', 2, inplace=True)
    return data

test_data = massage_data(test_data)
train_data = massage_data(train_data)

columns_for_fitting = ['Sex', 'CoPassengers', 'Pclass', 'Fare', 'Age', 'EmbarkedEnc']
data = [train_data, test_data]

X = train_data[columns_for_fitting]
y = train_data['Survived']
X1 = test_data[columns_for_fitting]

from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size=0.2, random_state=21)

from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
from sklearn import preprocessing
k = 4
while k < 5:
    k = k + 1
    X_train = preprocessing.StandardScaler().fit(X_train).transform(X_train.astype(float))
    model = KNeighborsClassifier(n_neighbors=k).fit(X_train, Y_train)
    X_test = preprocessing.StandardScaler().fit(X_test).transform(X_test.astype(float))
    predictions = model.predict(X_test)
    print('K and Accuracy are', k, accuracy_score(Y_test, predictions))