<jupyter_start><jupyter_text>Importing Libraries and Dataset<jupyter_code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import csv

%matplotlib inline

from sklearn.utils import shuffle
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
train=pd.read_csv(r"C:\Users\shruti\Desktop\Decodr Session Recording\Project\Decodr Project\Human behaviour project\train.csv")
test=pd.read_csv(r"C:\Users\shruti\Desktop\Decodr Session Recording\Project\Decodr Project\Human behaviour project\test.csv")
shuffle(train)
shuffle(test)
train.head(2)
train.tail(2)
train.shape
test.head(2)
test.tail(2)
test.shape
# Checking for Null values

print("Any missing value in Training set", train.isnull().values.any())
print("Any missing value in Testing set", test.isnull().values.any())<jupyter_output>Any missing value in Training set False
Any missing value in Testing set False<jupyter_text>Exploring Dataset<jupyter_code>train_outcome= pd.crosstab(index= train["Activity"], columns= "Count")
train_outcome<jupyter_output><empty_output><jupyter_text>Exploratory Data Analysis<jupyter_code>temp= train["Activity"].value_counts()
temp
df= pd.DataFrame({"labels": temp.index, "values": temp.values})
df.head(2)
labels= df["labels"]
sizes= df["values"]
colors= ["yellowgreen", "lightskyblue", "gold", "lightpink", "cyan", "lightcoral"]
patches, texts= plt.pie(sizes, colors=colors, labels=labels, shadow=True, startangle=90, pctdistance=1.1, labeldistance=1.2)
plt.legend(patches, labels, loc="right")
plt.axis("equal")
plt.tight_layout()
plt.show()<jupyter_output><empty_output><jupyter_text>Data Processing<jupyter_code>X_train= pd.DataFrame(train.drop(["Activity", "subject"], axis=1))
Y_train_label= train.Activity.values.astype(object)
X_test= pd.DataFrame(test.drop(["Activity", "subject"], axis=1))
Y_test_label= test.Activity.values.astype(object)
from sklearn import preprocessing
encoder= preprocessing.LabelEncoder()

encoder.fit(Y_train_label)
y_train= encoder.transform(Y_train_label)
y_train
encoder.fit(Y_test_label)
y_test= encoder.transform(Y_test_label)
y_test
num_cols= X_train._get_numeric_data().columns
num_cols
num_cols.size<jupyter_output><empty_output><jupyter_text>Model Building for Human Activity Recognition<jupyter_code>from sklearn.preprocessing import StandardScaler
scaler= StandardScaler()
x_train= scaler.fit_transform(X_train)
x_test= scaler.fit_transform(X_test)
knn= KNeighborsClassifier(n_neighbors=24)
knn.fit(x_train, y_train)
y_pred= knn.predict(x_test)
print((accuracy_score(y_test, y_pred)*100), "%")
scores=[]
for i in range(1,50):
    knn= KNeighborsClassifier(n_neighbors=i, n_jobs=-1)
    knn.fit(x_train, y_train)
    y_pred= knn.predict(x_test)
    scores.append(accuracy_score(y_test, y_pred))
plt.xlabel("Number of Neighbors")
plt.ylabel("Accuracy Score")
xticks= range(1,50)
plt.plot(xticks, scores, color="red", linestyle="solid", marker="o",
        markersize=5, markerfacecolor="blue")
plt.show()
scores= np.array(scores)
print("Optimal number of neighbor is:", scores.argmax())
print("Accuracy Score:" +str(scores.max()*100), "%")<jupyter_output>Optimal number of neighbor is: 19
Accuracy Score:90.29521547336275 %<jupyter_text>Conclusion<jupyter_code>knn= KNeighborsClassifier(n_neighbors=19)
knn.fit(x_train, y_train)
y_pred= knn.predict(x_test)
y_pred_label= list(encoder.inverse_transform(y_pred))
y_pred_label
print(confusion_matrix(Y_test_label, y_pred_label))
print(classification_report(Y_test_label, y_pred_label))<jupyter_output>precision    recall  f1-score   support

            LAYING       0.99      0.96      0.97       537
           SITTING       0.92      0.79      0.85       491
          STANDING       0.83      0.96      0.89       532
           WALKING       0.85      0.97      0.91       496
WALKING_DOWNSTAIRS       0.96      0.78      0.86       420
  WALKING_UPSTAIRS       0.89      0.92      0.90       471

          accuracy                           0.90      2947
         macro avg       0.91      0.90      0.90      2947
      weighted avg       0.91      0.90      0.90      2947
{'fraction_non_alphanumeric': 0.11785885741718675, 'fraction_numerical': 0.03720595295247239, 'mean_word_length': 4.836134453781512, 'pattern_counts': {'":': 2, '<': 22, '<?xml version=': 0, '>': 22, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '77704', 'license': 'Unlicense', 'n_tokens_mistral': 1588, 'n_tokens_neox': 1465, 'n_words': 287, 'path': 'Project6- Human Behavior Recognition.ipynb', 'repo_name': 'Shruti0630/Shruti_PythonProject6', 'size': '4166'}