<jupyter_start><jupyter_text>Human Activity Recognition Problem statement:In this project you will design a robust activity recogonition system based on the smartphones.As you know mobile devices have accelerometer as the sensor which collects the activities.These activities can be classified using K-nearest neighbour.   Attribute Information:For each record in the dataset it is provided:- Triaxial acceleration from the accelerometer (total acceleration) and the estimated body acceleration.- Triaxial Angular velocity from the gyroscope.- A 561-feature vector with time and frequency domain variables.- Its activity label.- An identifier of the subject who carried out the experiment.  step-1....Import requied libraries<jupyter_code># import the standard libraries
import pandas as pd #Data processing and I/O operation
import numpy as np #Linear Algebra
import matplotlib.pyplot as plt

%matplotlib inline

#Import the machine libraries
from sklearn.utils import shuffle
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report<jupyter_output><empty_output><jupyter_text>step-2... Import the Dataset<jupyter_code>train = shuffle(pd.read_csv('train.csv'))
test = shuffle(pd.read_csv('test.csv'))<jupyter_output><empty_output><jupyter_text>STep-3... Inspection of data<jupyter_code>train.head(10) ## shows top 10 rows
train.tail(1) ## Shows last row
train.shape ### size of trian data set
test.shape ## size of test data set<jupyter_output><empty_output><jupyter_text>Step-4...Data Exploration  Check for missing values<jupyter_code>print('Any missing value in training set:', train.isnull().values.any())
print('Any missing value in training set:', test.isnull().values.any())<jupyter_output>Any missing value in training set: False
Any missing value in training set: False<jupyter_text>Exploring the 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()  ### Gives 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)
## Import necessaray library 
from sklearn import preprocessing
## Instantiating the object
encoder = preprocessing.LabelEncoder()  ### It will do lable encoder
## Fit on train data
encoder.fit(Y_train_label)
y_train = encoder.transform(Y_train_label)
y_train
encoder.fit(Y_test_label)
## Transforming on test data
y_test = encoder.transform(Y_test_label)
y_test
num_cols = X_train._get_numeric_data().columns
num_cols.size<jupyter_output><empty_output><jupyter_text>Step-5.... Model Building<jupyter_code>from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
x_train = scaler.fit_transform(X_train)
x_test = scaler.fit_transform(X_test)
## Instantiating the object
knn = KNeighborsClassifier(n_neighbors=24)
## fit on train data
knn.fit(x_train,y_train)
## Predictions on test data
y_pred = knn.predict(x_test)
print((accuracy_score(y_test, y_pred)*100), '%')
## Applying the range method
scores = []  ###  creating Empty list
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 neighbors is:', scores.argmax())
print('Accuracy Score:' +str(scores.max()*100),'%')<jupyter_output>Optimal number of neighbors is: 19
Accuracy Score:90.29521547336275 %<jupyter_text>Step-6.......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.10874836784182056, 'fraction_numerical': 0.03077783995523223, 'mean_word_length': 4.722518676627534, 'pattern_counts': {'":': 0, '<': 34, '<?xml version=': 0, '>': 34, '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': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '653244', 'license': 'CC0-1.0', 'n_tokens_mistral': 1865, 'n_tokens_neox': 1727, 'n_words': 429, 'path': 'Human_Activity_Recognition (1) (1).ipynb', 'repo_name': 'SREELATHA-K/K_neighbors-', 'size': '5361'}