Dwebs Abstract

Understanding Human Behavior: Developing a Human Activity Recognition System with Machine Learning

By Naman Kumar, Dwebs Tutorial | Last Updated: 02-05-2024

Post Image

In an increasingly digital world, the ability to recognize and interpret human activities from sensor data holds immense value across various domains, including healthcare, sports analytics, and smart environments. Leveraging the power of machine learning, we embark on a journey to develop a robust human activity recognition system capable of accurately detecting and classifying activities based on sensor inputs. In this article, we delve into the methodologies, algorithms, and potential applications of machine learning in human activity recognition, offering insights into the dynamic field of activity monitoring and analysis.

  1. Data Collection and Preprocessing:Our journey begins with the acquisition of sensor data capturing human movements and behaviors, such as accelerometer and gyroscope readings from wearable devices or smartphone sensors. Through meticulous preprocessing steps including data cleaning, segmentation, and feature extraction, we ensure the quality and relevance of the data for model training and analysis.

  2. Feature Engineering and Selection:Next, we extract meaningful features from the raw sensor data to represent various aspects of human activities, such as temporal dynamics, frequency domain characteristics, and spatial orientations. Feature engineering techniques such as time-domain analysis, Fourier transforms, and principal component analysis (PCA) are employed to enhance the discriminative power of the features.

  3. Model Training and Evaluation:With our feature-engineered dataset prepared, we train machine learning models to learn patterns and relationships between sensor inputs and human activities. Supervised learning algorithms such as decision trees, support vector machines (SVM), and deep neural networks are explored to classify activities accurately. Models are evaluated using metrics such as accuracy, precision, recall, and F1-score to assess their performance and generalization capabilities.

  4. Real-Time Recognition and Deployment:Once trained and evaluated, our human activity recognition system is deployed into real-world environments, where it can perform real-time activity detection and classification. Whether deployed on wearable devices, smartphones, or IoT (Internet of Things) platforms, the system provides valuable insights into human behavior and facilitates applications such as health monitoring, fitness tracking, and context-aware computing.

  5. Applications and Future Directions:By accurately recognizing human activities, our system opens up a wide range of applications across various domains. From healthcare and rehabilitation to sports analytics and smart home automation, the ability to monitor and interpret human behavior in real-time has transformative potential. Future directions for research and development include exploring multimodal sensor fusion, transfer learning, and explainable AI techniques to further enhance the capabilities and interpretability of human activity recognition systems.

Download the Data set from Kaggle Repository or from below Download.

The below code is .Python file.

# %% [markdown]
# ## Human Activity Recognition

# %%
import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
import tensorflow as tf

from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.preprocessing import LabelEncoder
from tensorflow import keras
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

pd.set_option('display.max_columns', None)
sns.set_style('darkgrid')

# %%
## reading training data
train_df = pd.read_csv()
##reading test data
test_df = pd.read_csv()

# %%
train_df.head()

# %%
test_df.head()

# %%
print("train data shape: ", train_df.shape)
print("test data shape: ", test_df.shape)

# %%
## train and test data 
X_train = train_df.iloc[:, :-2]
y_train = train_df.iloc[:, -1]

X_test = test_df.iloc[:, :-2]
y_test = test_df.iloc[:, -1]

# %%
## unique classes
y_train.unique()

# %%
## value counts of unique classes
class_label = y_train.value_counts()

# %%
plt.figure(figsize=(10, 10))
plt.xticks(rotation=75)
sns.barplot(class_label.index, class_label);

# %%
## Standard Scaler
sc = StandardScaler()

X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

# %%
##  LabelEncoder

label_encoder = LabelEncoder()

y_train = label_encoder.fit_transform(y_train)
y_train=pd.get_dummies(y_train).values

y_test = label_encoder.fit_transform(y_test)
y_test=pd.get_dummies(y_test).values

# %%
## converting into numpy array
y_train = np.array(y_train)
y_test = np.array(y_test)

# %%
y_train

# %%
## PCA 
pca = PCA(n_components=None)

X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)

# %%
X_train

# %%
## Model 

model = keras.models.Sequential()
model.add(keras.layers.Dense(units=64,activation='relu'))
model.add(keras.layers.Dense(units=128,activation='relu'))
model.add(keras.layers.Dense(units=64,activation='relu'))
model.add(keras.layers.Dense(units=6,activation='softmax'))

# %%
model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])

# %%
history = model.fit(X_train, y_train, batch_size=128, epochs=15, validation_split=0.2)

# %%
## Loss Vs. Epochs

plt.figure(figsize=(10, 5))
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Test Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend(['Train Loss', 'Validation Loss']);

# %%
## Accuracy Vs. Epochs

plt.figure(figsize=(10, 5))
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Test Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend(['Train Accuracy', 'Validation Accuracy']);

# %%
## prediction

pred = model.predict(X_test)

# %%
predic = []

for p in pred:
    p = np.argmax(p)
    predic.append(p)

# %%
predic = np.array(predic)

# %%
y_test.shape

# %%
y_test[0]

y_test_label = []
for i in range(len(y_test)):
    for ind, j in enumerate(y_test[i]):
        if j == 1:
            y_test_label.append(ind)

# %%
y_test_label = np.array(y_test_label)

# %%
y_test_label

# %%
predic

# %%
print("Classification Report: \n", classification_report(y_test_label, predic))
print("-" * 100)
print()
print("Accuracy Score: ", accuracy_score(y_test_label, predic))
print("-" * 100)
print()
plt.figure(figsize=(10, 10))
sns.heatmap(confusion_matrix(y_test_label, predic), annot=True, fmt='g')

# %%

Conclusion

In conclusion, the application of machine learning in human activity recognition offers exciting opportunities to understand and interpret human behavior in diverse contexts. By leveraging sensor data and advanced algorithms, we can develop systems that accurately detect and classify activities, enabling a wide range of applications to improve health, performance, and quality of life.
"Stay tuned for future data science projects that will turbocharge your learning journey and take your skills to the next level!"

Download Code

Recommended Posts

Dwebs Image

Mastering Market Trends: Stock Price Prediction with Machine Learning

PYTHON

In the fast-paced world of finance, the ability to predict stock prices with accuracy is invaluable for investors, traders, and financial analysts alike. Leveraging the power of machine learning, we embark on a journey to develop predictive models capable of forecasting stock prices based on historical data spanning the last five years. In this article, we explore the methodologies, challenges, and potential applications of machine learning in stock price prediction, offering insights.

Dwebs Image

Start Your Own Social Media Management Agency: A Step-by-Step Guide

STARTUP
WFH

In today's digital age, the importance of a strong social media presence for businesses cannot be overstated. As platforms like Facebook, Instagram, and Twitter continue to dominate the online landscape, the demand for expert social media management services is at an all-time high. If you have a passion for social media and a knack for strategy, starting your own Social Media Management Agency could be the perfect entrepreneurial venture. In this guide, we'll walk you through the essential steps.