Hashwanth Gogineni's other Models Reports

Major Concepts


Sign-Up/Login to access Several ML Models and also Deploy & Monetize your own ML solutions for free

Models Home » Domain Usecases » Health Care and Pharmaceuticals » Stress Level Prediction using Heart Rate

Stress Level Prediction using Heart Rate

Models Status

Model Overview


Stress is a natural human emotion that affects everyone at some point in their lives. In truth, the human body is built to recognise and respond to stress. Your body develops physical and mental responses in response to changes or difficulties (stressors). That's what stress is. Your body's stress responses assist it in adapting to new surroundings. Stress can be beneficial in that it keeps us attentive, motivated, and prepared to avoid danger. A stress reaction, for example, may help your body work harder and stay awake longer if you have an important test coming up. When stressors persist without reprieve or moments of relaxation, it becomes a problem.


What happens to the body when you're stressed?

The autonomic nervous system regulates your heart rate, respiration, vision, and other bodily functions. The body's built-in stress reaction, known as the "fight-or-flight response," assists it in dealing with stressful conditions. Continuous activation of the stress response creates wear and tear on the body when a person is under long-term (chronic) stress. Symptoms manifest themselves in the form of physical, emotional, and behavioural manifestations.

The physical manifestations of stress include:

  • Aches and pains.

  • Chest pain or a feeling like your heart is racing.

  • Exhaustion or trouble sleeping.

  • Headaches, dizziness or shaking.

  • High blood pressure.

  • Muscle tension or jaw clenching.

  • Stomach or digestive problems.

  • Trouble having sex.

  • Weak immune system.

Stress can cause a variety of emotional and mental symptoms, including:

  • Anxiety or irritability.

  • Depression.

  • Panic attacks.

  • Sadness.

People who suffer from chronic stress frequently try to cope by engaging in unhealthy behaviours, such as:

  • Drinking alcohol too much or too often.

  • Gambling.

  • Overeating or developing an eating disorder.

  • Participating compulsively in sex, shopping or internet browsing.

  • Smoking.

  • Using drugs.

Why Stress Level Prediction?

The project can be used by healthcare companies to help detect stress levels in patients using Artificial intelligence.



The data is made up of numerous parameters derived from ECG signals obtained for different persons with different heart rates at the moment of measurement. 'SD1' and 'SD2' features, as well as 'sampen' and 'higuci' features, are all included in the dataset.

Random forest

Random forest is a supervised learning technique that can be used to classify and predict data. However, it is mostly employed to solve categorization issues. A forest, as we all know, is made up of trees, and more trees equals a more healthy forest. Similarly, the random forest method constructs decision trees from data samples, extracts predictions from each, and then votes on the best option. It's an ensemble method that's superior than a single decision tree because it averages the results to reduce over-fitting.

Working of Random Forest Algorithm

The following stages will help us understand how the Random Forest algorithm works −

  • Step 1 − Begin by selecting random samples from a given dataset.

  • Step 2 − Following that, this algorithm will create a decision tree for each sample. The forecast result from each decision tree will then be obtained.

  • Step 3 − Voting will take place in this phase for each expected outcome.

  • Step 4 − Finally, choose the prediction result with the most votes as the final prediction result.

Understanding Code

First, let us import the required libraries for the project.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import norm
from sklearn.preprocessing import LabelEncoder, StandardScaler
import pickle
from sklearn.model_selection import train_test_split
import joblib
from sklearn.metrics import classification_report

And now load the data into the system.


Also, let us look at a few important visualizations of our data.

df[['SD1', 'SD2']].hist()

import seaborn as sns

plt.title('condition Distribution')

Coming to the 'Data Preprocessing' part, let us search for missing values in the data.


As you can see no missing values exist in our data.

Now we need to encode the categorical values.

df['condition'] = df['condition'].replace({'no stress': 0, 'interruption': 1, 'time pressure' : 2})

Let us split the data into training and testing sets using the "train_test_split" function.

X = df.drop(columns=['condition', 'uuid', 'datasetId'])
Y = df['condition']

X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2)

Finally, we need to scale our data before feeding our data into a model.

scaler = StandardScaler()

X_train = pd.DataFrame(scaler.fit_transform(X_train), columns = X.columns)

X_test = pd.DataFrame(scaler.transform(X_test), columns = X.columns)

pickle.dump(scaler, open('scaler.pkl','wb'))

As you can see, I used the "StandardScaler" function to scale the data.

Now, let us dive deep into the modelling part of the project.

from sklearn.ensemble import RandomForestClassifier

rf_model= RandomForestClassifier()
rf_model.fit(X_train, y_train)
y_pred = rf_model.predict(X_test)
rf_model.score(X_train, y_train)*100

I used the "Random Forest" model to solve the problem.
As you can see, I used the "RandomForestClassifier" function to use the "Random Forest" algorithm.

Now let us have a look at the model's performance report.

from sklearn.metrics import classification_report
class_names = ['Patients who have no stress', 'Patients who are experiencing interruption pressure', 'Patients who are suffering from time pressure']
print(classification_report(y_test, y_pred, target_names=class_names))

As you can see, our model performed really well.

Thank you for your time.