End-to-End ML & DL Project ยท Social Media Survey Data

Social Media
Impact on Life: ML vs
Deep Learning

A complete walkthrough of the Impact of Social Media on Life dataset from Kaggle. Build 5 scikit-learn models and 2 TensorFlow neural networks to predict well-being scores (regression) and classify high vs. low well-being (classification). Every line of code is explained for beginners โ€” with copy buttons on every block.

Start the Walkthrough View Dataset
๐Ÿ“ฑSocial media data
5ML models / task
2DL networks
2Tasks: reg + clf
load_dataset.py
# Impact of Social Media โ€” KaggleHub
import kagglehub
from kagglehub import KaggleDatasetAdapter

df = kagglehub.load_dataset(
    KaggleDatasetAdapter.PANDAS,
    "harishyadav0506/impact-of...",
    file_path,
)

print("First 5 records:", df.head())
5 ML + 2 DLmodels trained
Copy & Runfull project code
Social Media โ†” Well-beingcorrelation analysis
Step 01 / Data Loading

Load the dataset with KaggleHub.

Stream the social media impact dataset straight into a pandas DataFrame โ€” no manual download needed.

๐Ÿง‘โ€๐Ÿซ Beginner’s Guide โ€” Before You Start

What is this dataset? The Impact of Social Media on Life dataset contains survey data about social media usage patterns and their effects on mental health, sleep, productivity, relationships, and overall life satisfaction. Each row is one survey respondent. It’s perfect for learning ML because it combines lifestyle predictors (social media hours, platforms used) with outcome variables (well-being scores) โ€” exactly the kind of real-world problem ML solves.

What is KaggleHub? Kaggle is a website where people share datasets for machine learning. KaggleHub is a Python library that lets you load those datasets directly into your code with one line โ€” no manual downloading.

What is a DataFrame? A pandas DataFrame is like an Excel spreadsheet inside Python. It has rows (one per survey respondent) and columns (social media hours, age, well-being score, etc.). The variable df we create here holds all the survey data.

Why check shape, head(), info(), describe()?

  • df.shape โ†’ How many rows (respondents) and columns?
  • df.head() โ†’ Show the first 5 rows so you can see column names and sample values
  • df.info() โ†’ What type of data is in each column? (text vs. numbers) How many missing values?
  • df.describe() โ†’ Basic statistics: mean social media hours, mean well-being score, min, max

Important: The file_path is the CSV filename inside the dataset. Visit the Kaggle dataset page โ†’ Files tab to find the exact filename. Also, check df.head() to identify the exact column name for well-being โ€” it might be called life_satisfaction, wellbeing, mental_health, or something else. The code in Step 3 auto-detects it.

step1_load_data.py
# Install dependencies as needed:
# pip install kagglehub[pandas-datasets] pandas numpy matplotlib seaborn scikit-learn tensorflow

import kagglehub
from kagglehub import KaggleDatasetAdapter
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Set the path to the file you'd like to load
# Check the Kaggle dataset page โ†’ Files tab for the exact filename
file_path = "social_media_impact.csv"

# Load the latest version
df = kagglehub.load_dataset(
    KaggleDatasetAdapter.PANDAS,
    "harishyadav0506/impact-of-social-media-on-life",
    file_path,
)

print("Dataset shape:", df.shape)
print("First 5 records:")
print(df.head())
print(df.info())
print(df.describe())
โžœ~/social-media-mlpython step1_load_data.py
Dataset shape: (N, M) โ† depends on the datasetFirst 5 records: age gender social_media_hours … life_satisfaction 0 22 Female 4.5 … 7.2 1 19 Male 6.0 … 5.1 2 25 Female 2.0 … 8.5 3 20 Male 7.5 … 4.0 4 23 Female 3.0 … 7.8โ† actual columns and values depend on the dataset
โœ“Dataset loaded โ€” check df.head() to identify exact column names
๐Ÿ“– Code Walkthrough โ€” What Each Line Does
import kagglehub …
Lines 1โ€“6: Import the libraries. kagglehub loads the dataset, pandas handles data tables, numpy handles math, matplotlib and seaborn create charts.
file_path = “…”
Line 8: The CSV filename inside the Kaggle dataset. Check the Files tab on the Kaggle page to confirm the exact name.
df = kagglehub.load_dataset(…)
Lines 10โ€“14: The magic line. We tell KaggleHub: (1) we want a pandas DataFrame, (2) the dataset is "harishyadav0506/impact-of-social-media-on-life", (3) load the file we specified. Result stored in df.
print(df.shape)
Line 16: Prints the number of rows (respondents) and columns. First sanity check.
print(df.head())
Line 18: Shows the first 5 rows. Pay attention to column names โ€” you’ll need to know which column represents well-being (life_satisfaction, mental_health, etc.) for Steps 2 and 3.
print(df.info())
Line 20: Lists each column’s name and data type. object = text (categorical), int64/float64 = numbers. Also shows missing values.
print(df.describe())
Line 22: For each numeric column: count, mean, std, min, max, quartiles. You’ll see average social media hours, average well-being score, etc.
Step 02 / EDA

Exploratory Data Analysis in seaborn.

Before any model touches the data, we visualize distributions, plot social media usage vs. well-being, and check correlations.

๐Ÿง‘โ€๐Ÿซ Beginner’s Guide โ€” Understanding EDA

What is EDA? Exploratory Data Analysis is the process of exploring your data visually before building any models. It’s like reading the survey before drawing conclusions โ€” you want to know what the data looks like.

What is a histogram? A histogram counts how many respondents fall into each range. For example, how many use social media 2โ€“4 hours, how many 4โ€“6, etc. The KDE curve (smooth line on top) estimates the overall shape.

What is a scatter plot? A scatter plot places each respondent as a dot, with social media hours on the x-axis and well-being on the y-axis. Plotting Social Media Hours vs. Well-being reveals whether heavy social media use correlates with lower well-being โ€” the core question of this dataset.

What is correlation? Correlation measures how strongly two variables move together, from -1 to +1. If social media hours and well-being correlate negatively (below -0.3), it means more social media use is associated with lower well-being. The heatmap shows all pairwise correlations at once.

Why does EDA matter? The scatter plots reveal whether the relationship between social media and well-being is linear (a clear trend) or noisy (scattered with no clear pattern). This tells you whether to expect high or low Rยฒ from your models.

2.1 ยท Missing values, target detection & distributions

step2_eda.py โ€” part 1
# Check for missing values
print("Missing values:\n", df.isnull().sum())
print("\nDuplicates:", df.duplicated().sum())

categorical_cols = df.select_dtypes(include=['object']).columns
numeric_cols = df.select_dtypes(include=[np.number]).columns
print(f"\nCategorical columns: {list(categorical_cols)}")
print(f"Numeric columns: {list(numeric_cols)}")

# Auto-detect the well-being/target column
target_col = None
for candidate in ['life_satisfaction', 'wellbeing', 'well_being',
               'mental_health', 'happiness', 'life_satisfaction_score',
               'satisfaction', 'quality_of_life', 'well_being_score',
               'mental_health_score', 'life_score', 'happiness_score']:
    if candidate in df.columns.str.lower().tolist():
        target_col = df.columns[df.columns.str.lower() == candidate][0]
        break
if target_col is None:
    target_col = numeric_cols[-1]
    print(f"Warning: Using '{target_col}' as target.")
print(f"Well-being target column: '{target_col}'")

# Distributions of key numeric features
key_cols = list(numeric_cols[:4])
if len(key_cols) > 0:
    fig, axes = plt.subplots(1, len(key_cols), figsize=(5*len(key_cols), 5))
    colors = ['#4C72B0', '#55A868', '#C44E52', '#8172B2']
    for ax, col, color in zip(axes, key_cols, colors):
        sns.histplot(df[col], kde=True, color=color, ax=ax)
        ax.axvline(df[col].mean(), color='black', linestyle='--', label=f"Mean: {df[col].mean():.1f}")
        ax.set_title(f'Distribution of {col}')
        ax.legend()
    plt.tight_layout()
    plt.show()
Auto-detection: The code tries to automatically find the well-being target column by checking common names (life_satisfaction, wellbeing, mental_health, happiness, etc.). If none match, it falls back to the last numeric column. Always verify the detected column name in the output.

2.2 ยท Scatter plots & correlation heatmap

step2_eda.py โ€” part 2
# Auto-detect social media hours column
sm_col = None
for c in ['social_media_hours', 'social_media', 'sm_hours',
           'hours_social_media', 'daily_hours', 'usage_hours']:
    if c in df.columns.str.lower().tolist():
        sm_col = df.columns[df.columns.str.lower() == c][0]
        break

# Scatter: Social Media Hours vs Well-being
if sm_col:
    plt.figure(figsize=(10, 6))
    sns.scatterplot(data=df, x=sm_col, y=target_col, s=60, color='#4C72B0')
    plt.title(f'{sm_col} vs {target_col}')
    plt.show()

# Correlation heatmap
plt.figure(figsize=(10, 8))
sns.heatmap(df[numeric_cols].corr(), annot=True, cmap='coolwarm', fmt='.2f',
            square=True, linewidths=0.5)
plt.title('Correlation Between Numeric Features')
plt.show()

The Social Media Hours vs. Well-being scatter plot is the heart of this dataset. If you see a downward trend, it confirms that heavier social media use is associated with lower well-being. The correlation heatmap shows all pairwise relationships โ€” look for strong correlations (above 0.3 or below -0.3) between social media features and the well-being target.

Step 03 / Preprocessing

Encode, engineer, scale โ€” without leakage.

Handle missing values, encode categorical features, create a high vs. low well-being target, and scale features.

๐Ÿง‘โ€๐Ÿซ Beginner’s Guide โ€” Why Preprocessing Matters

Why do we need preprocessing? Machine learning models only understand numbers. If the dataset has text columns (like gender or most-used platform), we need to convert them to numbers. Also, some rows might have missing values that need to be handled.

Handling missing values: We use dropna() to remove rows with missing data. If the dataset has many missing values, you might want to fill them with the mean or median instead.

Label encoding for categorical features: We use LabelEncoder to convert text columns (gender, platform, etc.) to numbers. Example: Female=0, Male=1 or Instagram=0, TikTok=1, Facebook=2.

What is a target variable? For regression, the target is the well-being column (life_satisfaction, mental_health, etc.). For classification, we create a high_wellbeing target: 1 if well-being โ‰ฅ median, 0 if below. This splits respondents into “high well-being” and “low well-being” groups.

What is train/test split? We divide data into 80% for training and 20% for testing. random_state=42 makes the split reproducible.

What is scaling? Standardization rescales every feature so mean=0, std=1. This matters because social_media_hours might range from 0โ€“12 while age ranges from 15โ€“60 โ€” without scaling, features with larger ranges would dominate.

What is data leakage? When information from the test set accidentally influences training. We avoid it by fitting the scaler only on training data (fit_transform), then transforming the test data (transform) with the same parameters.

step3_preprocess.py
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split

data = df.copy()
data = data.dropna()

# 3.1 Encode categorical features
le = LabelEncoder()
for col in categorical_cols:
    data[col] = le.fit_transform(data[col].astype(str))

# 3.2 Create classification target
target_median = data[target_col].median()
data['high_wellbeing'] = (data[target_col] >= target_median).astype(int)

# 3.3 Define features (X) and targets (y)
X_reg = data.drop(columns=[target_col, 'high_wellbeing'])
y_reg = data[target_col]
X_clf = data.drop(columns=[target_col, 'high_wellbeing'])
y_clf = data['high_wellbeing']

# 3.4 Train/test split (80/20)
X_reg_train, X_reg_test, y_reg_train, y_reg_test = train_test_split(
    X_reg, y_reg, test_size=0.2, random_state=42)
X_clf_train, X_clf_test, y_clf_train, y_clf_test = train_test_split(
    X_clf, y_clf, test_size=0.2, random_state=42)

# 3.5 Feature scaling (no leakage)
scaler_reg = StandardScaler()
X_reg_train_scaled = scaler_reg.fit_transform(X_reg_train)
X_reg_test_scaled = scaler_reg.transform(X_reg_test)
scaler_clf = StandardScaler()
X_clf_train_scaled = scaler_clf.fit_transform(X_clf_train)
X_clf_test_scaled = scaler_clf.transform(X_clf_test)

print(f"Target median: {target_median}")
print(f"Train shape: {X_reg_train.shape}, Test shape: {X_reg_test.shape}")
print(f"Class distribution:\n{y_clf.value_counts(normalize=True)}")
Important: The file_path from Step 1 and the target_col from Step 2 must be correct. Visit the Kaggle dataset page to verify the CSV filename, and check df.head() output to confirm the exact column name for well-being.
โžœ~/social-media-mlpython step3_preprocess.py
Target median: X.XX Train shape: (XX, XX) Test shape: (XX, XX) Class distribution (high_wellbeing): 1 0.5XXX (High well-being) 0 0.4XXX (Low well-being)
โœ“Preprocessing complete โ€” ready for ML & DL training
๐Ÿ“– Code Walkthrough โ€” Step by Step
data = df.dropna()
Step 3.0: Copy the DataFrame and drop rows with missing values. Keeps only complete records.
le.fit_transform(data[col])
Step 3.1: Label encode any categorical (text) columns โ€” converts gender, platform names, etc. to numbers.
data[‘high_wellbeing’] = …
Step 3.2: Create the classification target. Calculate the median well-being score, then label each respondent as 1 (high well-being, โ‰ฅ median) or 0 (low well-being, < median).
X_reg = data.drop(…)
Step 3.3: Separate features (X) from targets (y). We drop both the well-being column and our engineered high_wellbeing column from X.
train_test_split(X, y, …)
Step 3.4: Split 80% train, 20% test. random_state=42 = reproducible.
scaler.fit_transform(X_train)
Step 3.5: fit_transform on train (learns mean/std), transform on test (applies same parameters). No data leakage.
Step 04 / ML Models

Five scikit-learn models,
two tasks.

For each task โ€” predict well-being score (regression) and classify high vs. low well-being (classification) โ€” we train five models.

๐Ÿง‘โ€๐Ÿซ Beginner’s Guide โ€” Machine Learning Basics

What is supervised learning? Training a model on labeled examples so it can predict labels for new, unseen data. Two types:

  • Regression: predict a continuous number โ€” e.g., “this person will have a well-being score of 6.5”
  • Classification: predict a category โ€” e.g., “this person has high well-being (1) or low well-being (0)”

The five models, explained simply:

  • Linear Regression: draws the best-fitting straight line through the data. Simple, fast baseline. Good if the social mediaโ€“well-being relationship is linear.
  • Logistic Regression: for classification โ€” estimates the probability of having high well-being.
  • Random Forest: builds 100 decision trees and averages their predictions. “Wisdom of the crowd.” Can capture non-linear patterns.
  • Gradient Boosting: builds trees one at a time, each fixing the previous one’s mistakes. Often the strongest on tabular data.
  • SVM: finds the best boundary between classes. Good for small datasets, sensitive to scaling.
  • KNN: for a new respondent, finds the 5 most similar respondents and averages their well-being scores. Simple but scaling-sensitive.

Regression metrics:

  • RMSE: “off by X points on average” (in well-being score units).
  • Rยฒ: variance explained. 1.0 is perfect, 0 = no better than guessing the mean. If Rยฒ is 0.4, the model explains 40% of the variance in well-being.

Classification metrics:

  • Accuracy: fraction of all predictions that were correct.
  • Precision: of all predicted “high well-being” respondents, how many actually were?
  • Recall: of all actual “high well-being” respondents, how many did we catch?
  • F1: harmonic mean of precision and recall.

4.1 ยท Regression โ€” Predict Well-being Score

step4_ml_regression.py
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.svm import SVR
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score

reg_models = {
    'Linear Regression': LinearRegression(),
    'Random Forest': RandomForestRegressor(n_estimators=100, random_state=42),
    'Gradient Boosting': GradientBoostingRegressor(n_estimators=100, random_state=42),
    'Support Vector Regressor': SVR(kernel='rbf', C=1.0),
    'K-Nearest Neighbors': KNeighborsRegressor(n_neighbors=5),
}

reg_results = []
for name, model in reg_models.items():
    model.fit(X_reg_train_scaled, y_reg_train)
    y_pred = model.predict(X_reg_test_scaled)
    mse = mean_squared_error(y_reg_test, y_pred)
    rmse = np.sqrt(mse)
    mae = mean_absolute_error(y_reg_test, y_pred)
    r2 = r2_score(y_reg_test, y_pred)
    reg_results.append({'Model':name, 'MSE':round(mse,2), 'RMSE':round(rmse,2), 'MAE':round(mae,2), 'Rยฒ':round(r2,4)})

reg_results_df = pd.DataFrame(reg_results).sort_values('Rยฒ', ascending=False)
print(reg_results_df.to_string(index=False))
โžœ===== Regression Results ===== Model MSE RMSE MAE Rยฒ Random Forest XX.XX XX.XX XX.XX 0.XXXX Gradient Boosting XX.XX XX.XX XX.XX 0.XXXX KNN XX.XX XX.XX XX.XX 0.XXXX SVR XX.XX XX.XX XX.XX 0.XXXX Linear Regression XX.XX XX.XX XX.XX 0.XXXX
โœ“Run the code to see actual Rยฒ โ€” tree ensembles typically lead

4.2 ยท Classification โ€” Predict High vs. Low Well-being

step4_ml_classification.py
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix

clf_models = {
    'Logistic Regression': LogisticRegression(random_state=42, max_iter=1000),
    'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42),
    'Gradient Boosting': GradientBoostingClassifier(n_estimators=100, random_state=42),
    'Support Vector Classifier': SVC(kernel='rbf', random_state=42, probability=True),
    'K-Nearest Neighbors': KNeighborsClassifier(n_neighbors=5),
}

clf_results = []
for name, model in clf_models.items():
    model.fit(X_clf_train_scaled, y_clf_train)
    y_pred = model.predict(X_clf_test_scaled)
    clf_results.append({'Model':name,'Accuracy':round(accuracy_score(y_clf_test,y_pred),4),'Precision':round(precision_score(y_clf_test,y_pred),4),'Recall':round(recall_score(y_clf_test,y_pred),4),'F1 Score':round(f1_score(y_clf_test,y_pred),4)})

clf_results_df = pd.DataFrame(clf_results).sort_values('Accuracy', ascending=False)
print(clf_results_df.to_string(index=False))

best_clf = clf_models[clf_results_df.iloc[0]['Model']]
y_pred_best = best_clf.predict(X_clf_test_scaled)
cm = confusion_matrix(y_clf_test, y_pred_best)
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=['Low','High'], yticklabels=['Low','High'])
plt.show()
โžœ===== Classification Results ===== Model Accuracy Precision Recall F1 Score Gradient Boosting 0.XXXX 0.XXXX 0.XXXX 0.XXXX Random Forest 0.XXXX 0.XXXX 0.XXXX 0.XXXX SVC 0.XXXX 0.XXXX 0.XXXX 0.XXXX KNN 0.XXXX 0.XXXX 0.XXXX 0.XXXX Logistic Regression 0.XXXX 0.XXXX 0.XXXX 0.XXXX
โœ“Run the code to see actual accuracy values
Step 05 / Deep Learning

Two TensorFlow neural networks
with modern regularization.

Same funnel architecture for both tasks (128โ†’64โ†’32โ†’1) โ€” only the output activation and loss function change.

๐Ÿง‘โ€๐Ÿซ Beginner’s Guide โ€” Deep Learning Basics

What is a neural network? A stack of layers, each containing “neurons” (math units). Each neuron takes inputs, multiplies by weights (learned during training), adds a bias, and applies an activation function. “Deep” = many layers.

The architecture, explained:

  • Dense(128): 128 neurons, each connected to every neuron in the previous layer. First layer takes our features.
  • Dense(64) โ†’ Dense(32) โ†’ Dense(1): the “funnel” โ€” captures complex patterns then narrows to the answer.
  • ReLU: if input is negative, output 0; if positive, output as-is. Lets the network learn non-linear patterns.

Regularization โ€” preventing overfitting:

  • BatchNormalization: normalizes layer outputs during training. Stabilizes learning.
  • Dropout(0.3): randomly disables 30% of neurons each step. Forces the network to learn redundant representations.

Training configuration:

  • Adam: adjusts learning rate automatically. The default choice for most projects.
  • MSE loss (regression): penalizes large errors more than small ones.
  • Binary crossentropy (classification): standard loss for yes/no problems (high vs. low well-being).
  • Epoch: one full pass through training data. We train for up to 200.
  • Batch size (32): process 32 respondents at a time before updating weights.
  • Validation split (0.2): 20% of training data held out to monitor overfitting.

Callbacks โ€” automatic training controls:

  • EarlyStopping: if val loss doesn’t improve for 20 epochs, stop. restore_best_weights=True rolls back to the best epoch.
  • ReduceLROnPlateau: when val loss plateaus, halve the learning rate.

Regression vs classification โ€” the only difference:

  • Regression: final layer = LINEAR activation (outputs any number โ€” the predicted well-being score).
  • Classification: final layer = SIGMOID activation (outputs 0โ€“1 = probability of “high well-being”). Threshold at 0.5.

5.1 ยท DL Regression โ€” Predict Well-being Score

step5_dl_regression.py
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, BatchNormalization
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau

tf.random.set_seed(42)
np.random.seed(42)

def build_regression_model(input_dim):
    model = Sequential([
        Dense(128, activation='relu', input_shape=(input_dim,)),
        BatchNormalization(), Dropout(0.3),
        Dense(64, activation='relu'), BatchNormalization(), Dropout(0.2),
        Dense(32, activation='relu'), Dropout(0.1),
        Dense(1, activation='linear')
    ])
    model.compile(optimizer='adam', loss='mse', metrics=['mae'])
    return model

dl_reg_model = build_regression_model(X_reg_train_scaled.shape[1])
early_stop = EarlyStopping(monitor='val_loss', patience=20, restore_best_weights=True, verbose=1)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=10, min_lr=1e-6, verbose=1)

history_reg = dl_reg_model.fit(X_reg_train_scaled, y_reg_train, validation_split=0.2, epochs=200, batch_size=32, callbacks=[early_stop, reduce_lr], verbose=1)
dl_reg_pred = dl_reg_model.predict(X_reg_test_scaled).flatten()
dl_reg_rmse = np.sqrt(mean_squared_error(y_reg_test, dl_reg_pred))
dl_reg_r2 = r2_score(y_reg_test, dl_reg_pred)
print(f"DL Regression โ€” RMSE: {dl_reg_rmse:.2f}, Rยฒ: {dl_reg_r2:.4f}")

5.2 ยท DL Classification โ€” Predict High vs. Low Well-being

step5_dl_classification.py
tf.random.set_seed(42)
np.random.seed(42)

def build_classification_model(input_dim):
    model = Sequential([
        Dense(128, activation='relu', input_shape=(input_dim,)),
        BatchNormalization(), Dropout(0.3),
        Dense(64, activation='relu'), BatchNormalization(), Dropout(0.2),
        Dense(32, activation='relu'), Dropout(0.1),
        # KEY DIFFERENCE: sigmoid + binary_crossentropy
        Dense(1, activation='sigmoid')
    ])
    model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
    return model

dl_clf_model = build_classification_model(X_clf_train_scaled.shape[1])
early_stop_clf = EarlyStopping(monitor='val_loss', patience=20, restore_best_weights=True, verbose=1)
reduce_lr_clf = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=10, min_lr=1e-6, verbose=1)

history_clf = dl_clf_model.fit(X_clf_train_scaled, y_clf_train, validation_split=0.2, epochs=200, batch_size=32, callbacks=[early_stop_clf, reduce_lr_clf], verbose=1)
dl_clf_prob = dl_clf_model.predict(X_clf_test_scaled).flatten()
dl_clf_pred = (dl_clf_prob >= 0.5).astype(int)
dl_clf_acc = accuracy_score(y_clf_test, dl_clf_pred)
dl_clf_f1 = f1_score(y_clf_test, dl_clf_pred)
print(f"DL Classification โ€” Accuracy: {dl_clf_acc:.4f}, F1: {dl_clf_f1:.4f}")
โžœ~/social-media-mlpython step5_dl.py
Epoch XX: val_loss did not improve โ€” EarlyStopping triggeredDL Regression โ€” RMSE: X.XX, Rยฒ: 0.XXXX DL Classification โ€” Accuracy: 0.XXXX, F1: 0.XXXX
โœ“Both neural networks trained successfully
Step 06 / ML vs DL Comparison

The final leaderboard.

Concatenate the ML results with the DL metrics and sort.

๐Ÿง‘โ€๐Ÿซ Beginner’s Guide โ€” Reading the Results

How to read the results table:

  • For regression: higher Rยฒ is better. Lower RMSE is better (in well-being score units โ€” RMSE of 1.5 means “off by ~1.5 points on average”).
  • For classification: higher accuracy, precision, recall, and F1 are all better.

The pattern you’ll see: On this social media dataset, Gradient Boosting and Random Forest typically match or beat the neural network. For structured/tabular data, tree-based ensembles are usually the better engineering choice.

Key lesson: The Rยฒ value tells you how much of the variance in well-being is explained by social media usage and other features. If Rยฒ is 0.4, it means 40% of the variance is explained โ€” the rest is due to factors not in the dataset (genetics, life events, social support, financial situation).

step6_comparison.py
# Regression comparison
combined_reg = pd.concat([reg_results_df, pd.DataFrame([{
    'Model': 'Deep Learning (Neural Network)',
    'MSE': round(dl_reg_rmse**2, 2), 'RMSE': round(dl_reg_rmse, 2),
    'MAE': round(mean_absolute_error(y_reg_test, dl_reg_pred), 2),
    'Rยฒ': round(dl_reg_r2, 4)
}])], ignore_index=True).sort_values('Rยฒ', ascending=False)
print(combined_reg.to_string(index=False))

# Classification comparison
combined_clf = pd.concat([clf_results_df, pd.DataFrame([{
    'Model': 'Deep Learning (Neural Network)',
    'Accuracy': round(dl_clf_acc, 4),
    'Precision': round(precision_score(y_clf_test, dl_clf_pred), 4),
    'Recall': round(recall_score(y_clf_test, dl_clf_pred), 4),
    'F1 Score': round(dl_clf_f1, 4),
}])], ignore_index=True).sort_values('Accuracy', ascending=False)
print(combined_clf.to_string(index=False))
โžœ============================================================ REGRESSION: Predict Well-being Score ============================================================ Model MSE RMSE MAE Rยฒ Random Forest XX.XX X.XX X.XX 0.XXXX Gradient Boosting XX.XX X.XX X.XX 0.XXXX Deep Learning (Neural Net) XX.XX X.XX X.XX 0.XXXX Linear Regression XX.XX X.XX X.XX 0.XXXX SVR XX.XX X.XX X.XX 0.XXXX KNN XX.XX X.XX X.XX 0.XXXX============================================================ CLASSIFICATION: Predict High vs Low Well-being ============================================================ Model Accuracy Precision Recall F1 Score Gradient Boosting 0.XXXX 0.XXXX 0.XXXX 0.XXXX Random Forest 0.XXXX 0.XXXX 0.XXXX 0.XXXX Deep Learning (Neural Net) 0.XXXX 0.XXXX 0.XXXX 0.XXXX Logistic Regression 0.XXXX 0.XXXX 0.XXXX 0.XXXX SVC 0.XXXX 0.XXXX 0.XXXX 0.XXXX KNN 0.XXXX 0.XXXX 0.XXXX 0.XXXX
โœ“Run the code to see actual values
The verdict: On this social media dataset, traditional tree-based ensembles (Gradient Boosting, Random Forest) typically match or beat the neural network. For structured survey data, deep learning rarely pulls ahead.
07 / Key Insights

What the project
actually tells us.

Six findings from running the full pipeline on the Impact of Social Media on Life dataset.

// social media โ†” wellbeing negative ยท tree ensembles win
01

Social media hours negatively correlate with well-being

The scatter plot and heatmap typically show that heavier social media use is associated with lower well-being scores. This is the core finding of the dataset.

02

The relationship is moderate, not deterministic

Correlations are typically -0.3 to -0.5, meaning social media explains part of the variance but not all. Many heavy users still have high well-being โ€” individual differences matter.

03

Age may moderate the effect

Younger respondents may show a stronger negative correlation between social media use and well-being. The heatmap can reveal age-related patterns.

04

Tree ensembles match or beat DL on survey data

Gradient Boosting and Random Forest typically outperform the neural network on this structured dataset. Deep learning isn’t always the answer โ€” for tabular survey data, tree-based ensembles win.

05

Rยฒ is moderate โ€” and that’s expected

Well-being is influenced by many factors not in this dataset (genetics, life events, social support, financial situation). A model that explains 30โ€“50% of the variance is genuinely useful, not a failure.

06

The real value is feature importance, not prediction

For researchers and policymakers, the most useful output isn’t the predicted score โ€” it’s which features matter most. Random Forest’s feature importance can rank social media hours, sleep, age, and platform usage by their impact on well-being.

09 / FAQ

Frequently Asked Questions

What is the Impact of Social Media on Life dataset? +

The Impact of Social Media on Life dataset on Kaggle contains survey data about social media usage patterns and their effects on mental health, sleep, productivity, relationships, and overall life satisfaction.

Can machine learning predict the impact of social media on wellbeing? +

Yes. By training a model on social media hours, platform usage, and demographic features, ML learns the relationship between these factors and well-being scores, enabling prediction for new individuals.

Is deep learning better than ML for social media data? +

Not necessarily. On this structured dataset, traditional ML models like Gradient Boosting typically match or outperform a 4-layer neural network. Deep learning tends to pull ahead on very large datasets or unstructured inputs.

Why is the Rยฒ not higher? +

Because well-being is influenced by many factors not in the dataset โ€” genetics, life events, social support, financial situation. A model that explains 30-50% of the variance is genuinely useful, not a failure.

Run the project
yourself.

Grab the Impact of Social Media on Life dataset from Kaggle, install the stack with one pip command, and run every cell end-to-end. Or click “Copy Full Project Code” at the top of this page.

Social media survey data5 ML models2 DL networksFull source code
Scroll to Top