Learn with LSGP

Data Science

Turn raw data into insight, prediction, and decisions — from cleaning and EDA to machine learning and communication, by Learn with LSGP.

Python & Pandas
Statistics
Data Cleaning
EDA & Visualization
Machine Learning
Model Evaluation

🔬

1. What Is Data Science?

Data Science is the discipline of extracting knowledge and actionable insight from data using a combination of programming, mathematics, statistics, and domain expertise. It sits at the intersection of three overlapping fields: computer science (tools and algorithms), statistics (methods for reasoning under uncertainty), and subject-matter expertise (understanding what the data actually means in context). A data scientist who is strong in all three areas is rare and extraordinarily valuable.

The phrase "data science" became mainstream around 2012, but the underlying work — statistical modelling, experimental design, pattern recognition — is much older. What changed is scale: modern organisations collect data at a volume and speed that was unimaginable 20 years ago, and that data contains genuine business intelligence that skilled analysts can surface. Learn with LSGP's Data Science track is designed to build all three dimensions — not just the Python skills, but the statistical intuition and the ability to communicate findings clearly to non-technical stakeholders.

Data Science vs Related Fields

Data Science

Full workflow: data collection → cleaning → analysis → modelling → communication. Broad generalist role focused on insight generation.

Data Engineering

Builds the pipelines and infrastructure that move and store data. Focuses on ETL, data warehouses, Spark, Kafka — the plumbing that feeds data scientists.

ML Engineering

Takes trained models and deploys them reliably at scale. Focuses on model serving, A/B testing, feature stores, and production ML systems.

Data Analyst

Focuses on reporting, dashboards, and descriptive statistics. Less modelling, more SQL, Tableau, and business intelligence tools.

AI / Research

Develops new algorithms and models — deep learning architectures, reinforcement learning methods. Requires heavy mathematics and PhD-level research skills.

💡 Learn with LSGP Perspective As an Indian CS/IT student, the most accessible entry point to data science is through Python + statistics + one ML framework (scikit-learn). Master these three, build three end-to-end projects with real datasets, and you are competitive for analyst and junior data scientist roles at Indian startups, product companies, and consulting firms.

🔄

2. The Data Science Pipeline

Every data science project — whether predicting customer churn, classifying medical images, or forecasting stock prices — follows the same fundamental pipeline. Understanding this pipeline end-to-end is what separates someone who can run a Jupyter notebook from a data scientist who can deliver value on a real project. Each stage has its own skills, tools, and failure modes, and time spent on each varies wildly by project.

📊 Data Science Project Pipeline

1
Problem Definition
What question are we answering? What does success look like?
2
Data Collection
APIs, databases, web scraping, surveys, public datasets
3
Data Cleaning
Handle nulls, fix types, remove duplicates, detect outliers
4
Exploratory Analysis
Distributions, correlations, visualisations, hypotheses
5
Feature Engineering
Transform raw data into informative model inputs
6
Modelling
Train, tune, compare algorithms on your data
7
Evaluation
Metrics, cross-validation, bias-variance analysis
8
Communication & Deploy
Charts, reports, dashboards, or API-served predictions

In practice, this pipeline is not linear — it is a loop. EDA often reveals data quality issues that send you back to cleaning. Modelling results often reveal that you need new features, which sends you back to feature engineering. A real project might cycle through steps 3–6 a dozen times before reaching a deployable model. Learn with LSGP's project-based approach trains you to navigate this iteration, not just execute each step in isolation.

🎬 Data Transformation Flow (Animated)

Raw Data → Model-Ready Features
🗃️
Raw CSV
🧹
Clean
🔍
EDA
⚙️
Feature Eng.
📐
Scale / Encode
🤖
Model Input

🧹

3. Data Cleaning

Industry professionals consistently report spending 60–80% of their project time on data cleaning and preparation — not on glamorous modelling. This is not a failure of tools or process; it reflects the fundamental reality that real-world data is messy. Survey respondents leave fields blank. Sensors malfunction. Manual data entry introduces typos. Timestamps come in seven different formats. A model trained on dirty data will learn and amplify those errors. Clean data is not just a starting condition — it is the most important determinant of model quality.

Common Data Quality Problems

Missing Values

Fields left blank or recorded as NaN/None. Strategies: drop rows, fill with mean/median/mode, forward-fill time-series, or predict with another model.

Outliers

Values far outside the normal range. May be data errors or genuine extremes. Use IQR method or Z-score to detect. Decide per-feature whether to remove, cap, or keep.

Duplicates

Same record appearing multiple times due to data entry errors or join problems. Pandas df.duplicated() detects; df.drop_duplicates() removes.

Wrong Types

Numerical columns stored as strings; dates stored as plain text. Must cast explicitly before any computation or visualisation.

Inconsistent Strings

"Mumbai", "mumbai", "MUMBAI", "Mumbaii" — all mean the same city. Requires lowercase normalisation, whitespace stripping, and fuzzy deduplication.

Class Imbalance

In classification, if 99% of samples are class A, a model that always predicts A looks 99% accurate but is useless. Handle with oversampling (SMOTE) or class weights.

Data Cleaning in Python

data_cleaning.py — common patterns
import pandas as pd
import numpy as np

df = pd.read_csv('students.csv')

# 1. Inspect the data
print(df.info())          # dtypes, non-null counts
print(df.isnull().sum())  # missing per column

# 2. Fill missing numerical values with median
df['score'] = df['score'].fillna(df['score'].median())

# 3. Drop rows missing critical fields
df = df.dropna(subset=['student_id', 'name'])

# 4. Fix inconsistent strings
df['city'] = df['city'].str.strip().str.lower()

# 5. Remove duplicates
df = df.drop_duplicates(subset=['student_id'])

# 6. Cap outliers at 1.5 × IQR
Q1, Q3 = df['score'].quantile([0.25, 0.75])
IQR = Q3 - Q1
df['score'] = df['score'].clip(Q1 - 1.5*IQR, Q3 + 1.5*IQR)

📊

4. Exploratory Data Analysis (EDA)

Exploratory Data Analysis is the detective phase of a data science project. Before building any model, you need to understand your data deeply: what does each variable's distribution look like? Which variables are correlated with the target? Are there suspicious patterns that might indicate data quality issues? EDA answers these questions through summary statistics and visualisations, and it directly informs every modelling decision you make downstream.

🎬 Score Distribution Across Course Levels (Animated)

Average Student Score by Course Level — Learn with LSGP Sample Data
62
Beginner
74
Elementary
81
Intermediate
79
Upper-Int
88
Advanced
91
Expert

📊 Scatter Plot — Study Hours vs Score

Study Hours per Week Score (%) 5 10 15 20 25 30 40 60 80 95 trend Positive correlation visible — longer study sessions → higher scores

EDA Questions to Always Ask

  • Shape and size: How many rows? How many features? What are the dtypes?
  • Distributions: Are numerical features normally distributed? Skewed? Bimodal? Look at histograms.
  • Correlations: Which features are correlated with the target variable? Use a correlation heatmap.
  • Cardinality: How many unique values do categorical features have? High-cardinality categoricals need special encoding.
  • Temporal patterns: If there is a date column, do you see seasonality, trends, or sudden shifts?
  • Class balance: For classification tasks, what is the distribution of the target classes?

📺 Recommended Video — EDA with Python

Exploratory Data Analysis with Pandas & Matplotlib — clear, practical tutorial

📐

5. The Statistics Foundation

Statistics is the language of uncertainty — and data science is entirely about making decisions under uncertainty. Every machine learning algorithm, every A/B test conclusion, every confidence interval is built on statistical foundations. Many data science practitioners skip statistics and go straight to models, then produce results they cannot interpret or defend. Learn with LSGP considers statistical thinking non-negotiable.

Core Statistical Concepts

ConceptWhat It MeansWhy It Matters in DS
Mean / Median / ModeMeasures of central tendencyMedian is robust to outliers; always check both for skewed data
Variance / Std DevSpread of values around the meanHigh variance → unstable model; normalisation needed
Correlation (r)Linear relationship strength, −1 to +1Feature selection; multicollinearity detection
p-valueProbability of seeing data this extreme if H₀ is trueA/B test conclusions; feature significance testing
Central Limit TheoremMeans of large samples are normally distributedJustifies using normal-distribution tests on real data
Confidence IntervalRange likely to contain the true population parameterReporting model performance with uncertainty bounds
Bayes' TheoremP(A|B) = P(B|A)·P(A) / P(B)Foundation of Naive Bayes classifier and Bayesian ML

Probability Distributions You Must Know

Normal (Gaussian)

Bell-shaped, symmetric. Describes heights, test scores, errors in measurements. Central to regression assumptions.

Binomial

Count of successes in n independent Bernoulli trials. Click-through rates, defect counts.

Poisson

Count of events in a fixed time period. Website visits per hour, support tickets per day.

Uniform

All values equally likely. Used in random sampling, simulation initialisation.


🤖

6. Machine Learning Fundamentals

Machine Learning is the branch of AI where systems learn patterns from data rather than being explicitly programmed. Instead of writing rules ("if price > 500 and area > 1000 then label = expensive"), you feed labelled examples to an algorithm that discovers the rules itself. The three main categories — supervised, unsupervised, and reinforcement learning — each apply to different types of problems.

🎬 Algorithm Selection Map

Supervised · Regression
Linear Regression

Predicts a continuous value (price, temperature, score) as a weighted sum of input features. Fast, interpretable, requires linear relationship.

Supervised · Classification
Logistic Regression

Predicts class probability using the sigmoid function. Despite the name, it is a classification algorithm. Great baseline for binary problems.

Supervised · Both
Decision Trees

Splits data by feature thresholds, forming a tree of if-else rules. Highly interpretable. Prone to overfitting alone — combine into Random Forests.

Supervised · Both
Random Forest

Ensemble of decision trees trained on bootstrap samples, predictions averaged (regression) or voted (classification). Reduces overfitting dramatically.

Supervised · Both
Gradient Boosting

Builds trees sequentially, each correcting the errors of the previous. XGBoost and LightGBM are the dominant implementations — win most Kaggle competitions.

Unsupervised · Clustering
K-Means

Partitions data into K clusters by minimising within-cluster variance. Customer segmentation, document grouping, anomaly detection.

Unsupervised · Dim. Reduction
PCA

Principal Component Analysis projects high-dimensional data to fewer dimensions preserving maximum variance. Visualisation, noise reduction, feature compression.

Supervised · Classification
Support Vector Machine

Finds the hyperplane that maximises margin between classes. Effective in high-dimensional spaces. Kernel trick enables non-linear boundaries.

A Complete scikit-learn Workflow

ml_pipeline.py — train and evaluate a classifier
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.metrics import classification_report
import pandas as pd

# Load cleaned data
df = pd.read_csv('students_clean.csv')
X = df.drop('passed', axis=1)
y = df['passed']

# Split: 80% train, 20% test — always split BEFORE any preprocessing
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# Build a pipeline (prevents data leakage)
pipe = Pipeline([
    ('scaler', StandardScaler()),
    ('clf',    RandomForestClassifier(n_estimators=100, random_state=42))
])

# Train
pipe.fit(X_train, y_train)

# Cross-validation score (more reliable than single split)
cv_scores = cross_val_score(pipe, X_train, y_train, cv=5, scoring='f1')
print(f"CV F1: {cv_scores.mean():.3f} ± {cv_scores.std():.3f}")

# Final evaluation on held-out test set
y_pred = pipe.predict(X_test)
print(classification_report(y_test, y_pred))

📺 Recommended Video — Machine Learning Explained

But what is a Neural Network? — 3Blue1Brown (best visual introduction to ML concepts)

🎯

7. Model Evaluation

Building a model is easy. Knowing whether it is actually good — and good enough for your specific problem — is hard. Model evaluation requires choosing the right metrics for your problem, understanding the bias-variance trade-off, and ensuring your evaluation procedure does not introduce data leakage. A model that looks 99% accurate in evaluation but fails in production is worse than useless — it generates false confidence.

📊 Confusion Matrix (Classification)

Predicted →
Predicted Positive
Predicted Negative
Actual Positive
TP ✅
True Positive
FN ❌
False Negative
Actual Negative
FP ❌
False Positive
TN ✅
True Negative

Key Evaluation Metrics

Accuracy = (TP+TN) / Totalmisleading on imbalanced data
Precision = TP / (TP+FP)when false positives are costly
Recall = TP / (TP+FN)when false negatives are costly
F1 Score = 2 × (P × R) / (P + R)harmonic mean of precision & recall

Bias-Variance Trade-off

Underfitting (High Bias)

Model is too simple to capture patterns. High training error AND high test error. Fix: more complex model, more features, fewer regularisation constraints.

Overfitting (High Variance)

Model memorises training data including noise. Low training error, high test error. Fix: more training data, regularisation (L1/L2), dropout, cross-validation.

Good Fit

Training and validation errors are both low and close together. Model generalises well to unseen data — the goal of every ML workflow.

Cross-Validation

Split data into K folds; train on K-1, validate on 1, rotate K times. Final metric is averaged. 5-fold or 10-fold cross-validation is standard practice.


🛠️

8. Tools, Communication & Career

Data science is not just a technical skill — it is a communication skill. The most valuable data scientists are those who can clearly explain their findings to stakeholders who do not write code: business managers, product managers, executives. A beautiful model that nobody understands and nobody acts on has zero business value. Learn with LSGP builds communication skills explicitly into the data science curriculum because this is where most technical courses fall short.

Essential Data Science Stack

LayerToolWhat It Does
LanguagePythonPrimary language for DS. Readable, huge ecosystem, dominant in industry.
Data manipulationPandasDataFrame operations, cleaning, groupby, merge, reshape.
Numerical computingNumPyFast array operations, linear algebra, random sampling.
VisualisationMatplotlib / SeabornStatic charts. Seaborn adds statistical plot types with less code.
Interactive vizPlotlyInteractive charts for notebooks and dashboards.
MLscikit-learnUnified API for classical ML algorithms, preprocessing, evaluation.
Deep learningPyTorch / TensorFlowNeural networks for images, text, sequences.
NotebooksJupyter / Google ColabInteractive code + markdown + visualisations in one document.
Data storageSQL (PostgreSQL)Query structured data in databases — essential for real projects.
Version controlGit + DVCTrack code changes (Git) and dataset/model versions (DVC).

Communicating Findings Effectively

  • Lead with the answer, not the methodology. Executives want "churn is highest in users who haven't logged in for 14+ days" — not "we trained a gradient boosting classifier with F1=0.83."
  • Use the right chart for the message. Bar charts for comparison. Line charts for trends over time. Scatter plots for relationships. Pie charts almost never.
  • State uncertainty honestly. A confidence interval or error bar communicates that your finding has limits. This builds trust — stakeholders who understand uncertainty make better decisions.
  • Know your audience. A presentation to data engineers is different from one to the marketing team. Adjust technical depth accordingly.
  • One slide, one insight. A crowded dashboard that shows everything simultaneously communicates nothing. Each visualisation should answer one specific question.

Building Your Data Science Portfolio

Project 1: EDA Story

Pick a public dataset (Kaggle, UCI, data.gov.in). Write a complete EDA notebook with 10+ visualisations and written conclusions. Shows communication skills.

Project 2: Classification

Binary classification on a real-world problem (loan default, disease detection, customer churn). Compare 3 algorithms. Report with confusion matrices and F1 scores.

Project 3: End-to-End

Full pipeline from raw CSV to a deployed web API (Flask or FastAPI) serving predictions. Shows engineering skills alongside data skills.

Project 4: Domain-Specific

Choose a domain you care about (finance, health, agriculture, sports). Domain knowledge + data science is where the highest-value work happens.

📺 Recommended Video — Data Science Career Roadmap

How to Become a Data Scientist in 2024 — realistic roadmap for Indian students
🚀 Learn with LSGP Data Science Track Learn with LSGP's Data Science module guides you from pandas basics through EDA, classical ML, model evaluation, and project deployment with step-by-step notebooks, curated datasets, and project templates. Every concept on this page has a corresponding hands-on exercise. The best way to learn data science is by doing data science — start your first project today.

← Back to Learn with LSGP