0% found this document useful (0 votes)
19 views19 pages

ML Notes Interview

The document provides an overview of essential Python libraries and machine learning concepts, including data manipulation with pandas, numerical computations with numpy, and visualization with matplotlib. It explains various machine learning algorithms, their intuitions, and applications, alongside important concepts like supervised vs unsupervised learning, overfitting, and feature encoding. Additionally, it covers model evaluation metrics, deployment steps, and common challenges in machine learning projects.

Uploaded by

ashemle508
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views19 pages

ML Notes Interview

The document provides an overview of essential Python libraries and machine learning concepts, including data manipulation with pandas, numerical computations with numpy, and visualization with matplotlib. It explains various machine learning algorithms, their intuitions, and applications, alongside important concepts like supervised vs unsupervised learning, overfitting, and feature encoding. Additionally, it covers model evaluation metrics, deployment steps, and common challenges in machine learning projects.

Uploaded by

ashemle508
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

📦 1.

pandas

Used for: Data manipulation and analysis


Why it's important: It allows you to clean, filter, transform, and explore
your dataset efficiently.

🧠 Example:

python

CopyEdit

import pandas as pd

df = pd.read_csv("[Link]")

[Link]()

[Link]()

[Link]("category").mean()

➗ 2. numpy

Used for: Fast numerical computations, arrays, and matrices


Why it's important: ML models work with numerical arrays; NumPy
powers most operations under the hood.

🧠 Example:

python

CopyEdit

import numpy as np

a = [Link]([1, 2, 3])

[Link](a)

[Link](a, a)

📊 3. matplotlib

Used for: Creating visualizations (line charts, histograms, etc.)


Why it's important: Helps you understand your data and detect trends
or outliers.

🧠 Example:

python
CopyEdit

import [Link] as plt

[Link](df['sales'])

[Link]()

🤖 4. scikit-learn (sklearn)

✅ a) train_test_split

Used for: Splitting data into training and test sets.

python

CopyEdit

from sklearn.model_selection import train_test_split

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

🧼 b) StandardScaler

Used for: Scaling features to have mean = 0 and std = 1 (important for
many ML models).

python

CopyEdit

from [Link] import StandardScaler

scaler = StandardScaler()

X_scaled = scaler.fit_transform(X)

🔄 c) Pipeline

Used for: Chaining preprocessing and model steps into one object.

python

CopyEdit

from [Link] import Pipeline

pipe = Pipeline([

('scaler', StandardScaler()),
('model', LogisticRegression())

])

[Link](X_train, y_train)

🔍 d) GridSearchCV

Used for: Hyperparameter tuning — tries different combinations and


picks the best.

python

CopyEdit

from sklearn.model_selection import GridSearchCV

params = {'C': [0.1, 1, 10]}

grid = GridSearchCV(LogisticRegression(), param_grid=params)

[Link](X_train, y_train)

🧠 5. TensorFlow / PyTorch (Basic Overview)

You don’t need deep coding knowledge, but know what they are:

🔷 TensorFlow

 Developed by Google

 Widely used for deep learning (Neural Networks, CNNs, RNNs)

 Uses static computation graphs

🔶 PyTorch

 Developed by Facebook

 Easier for research and prototyping

 Uses dynamic computation graphs (easier to debug)

📌 Both support building and training deep learning models like:

 Image classifiers

 Time-series predictors

 NLP models
Algorithms:

🔍 1. Linear Regression

Intuition:
It draws a straight line through the data to predict a continuous value.
It tries to find the best-fit line that minimizes the error between
predicted and actual values.

🧠 Think of it like:

"How can I draw a line that comes as close as possible to all the points?"

✅ 2. Logistic Regression

Intuition:
It predicts probability of a class, like yes/no, 0/1, using a sigmoid
curve.
Even though it’s called "regression", it's used for classification.

🧠 Think of it like:

"Can I estimate how likely something belongs to a certain class?"

🌳 3. Decision Trees

Intuition:
It splits the data based on feature values in a tree-like structure,
making decisions at each "node" to reach a final prediction.

🧠 Think of it like:

"A flowchart where each question leads to a final decision."

🌲 4. Random Forest

Intuition:
It builds multiple decision trees and takes the majority vote (for
classification) or average (for regression).
This reduces overfitting and increases accuracy.

🧠 Think of it like:

"A committee of trees making better decisions than just one tree."

🚀 5. Support Vector Machine (SVM)


Intuition:
It tries to find the best boundary (hyperplane) that separates different
classes with the maximum margin.
It can also handle non-linear data using kernels.

🧠 Think of it like:

"Let’s draw the widest possible gap between classes so new points can be
clearly separated."

👯‍♂️6. K-Nearest Neighbors (KNN)

Intuition:
It classifies a new point based on the 'K' closest points to it in the
dataset.
No training happens; it stores data and predicts by majority vote.

🧠 Think of it like:

"You are most likely to belong to the same group as your closest
neighbors."

🔵 7. K-Means Clustering

Intuition:
It groups data into K clusters by minimizing the distance between points
and their cluster centers.
Used in unsupervised learning.

🧠 Think of it like:

"Let’s find natural groupings in data by pulling similar items together."

🎯 8. PCA (Principal Component Analysis)

Intuition:
It reduces the number of features while keeping the most important
information by finding new axes (principal components) that explain the
most variance.

🧠 Think of it like:

"Let’s shrink our data to fewer dimensions while preserving its essence."

✅ Bonus Tip:
In your interview, follow this structure:

“This algorithm is used for… It works by... A real-world example


would be...”
This shows both technical and practical understanding.

🧠 Machine Learning Concepts

1. What is the difference between supervised and unsupervised


learning?

Answer:
Supervised learning uses labeled data — the model learns from input-
output pairs (like predicting house prices from past data).
Unsupervised learning uses unlabeled data — the model tries to find
patterns or groupings in the data (like customer segmentation using
clustering).

2. What is overfitting and how can you prevent it?

Answer:
Overfitting happens when a model performs well on training data but
poorly on new, unseen data — it "memorizes" rather than "learns".
It can be prevented by:

 Using simpler models

 Cross-validation

 Regularization (L1, L2)

 More training data

 Early stopping in deep learning

3. Explain bias vs variance.

Answer:

 Bias: Error due to overly simple assumptions. High bias =


underfitting.

 Variance: Error due to model being too sensitive to training data.


High variance = overfitting.
We aim for a balance: low bias + low variance.
4. How do you evaluate a regression model?

Answer:

 MAE (Mean Absolute Error): Average absolute errors.

 MSE (Mean Squared Error): Penalizes large errors more.

 RMSE: Square root of MSE.

 R² Score: Measures how well the model explains variance in data


(closer to 1 is better).

5. What is the difference between bagging and boosting?

Answer:

 Bagging (Bootstrap Aggregating): Trains multiple models


independently and averages their results. Example: Random Forest.

 Boosting: Trains models sequentially, where each new model


corrects errors of the previous. Example: XGBoost, AdaBoost.

🧪 Python / scikit-learn Questions

6. How do you handle missing values in a dataset using pandas?

Answer:

python

CopyEdit

[Link]() # Removes rows with missing values

[Link](0) # Replaces missing values with 0

[Link]([Link]()) # Replaces with mean (for numerical columns)

7. What is the difference between fit() and fit_transform()?

Answer:

 fit() learns parameters (like mean & std for scaling).

 fit_transform() does both: learns and applies transformation.


Used during training; only transform() is used on test data.
📊 Data Processing & Statistics

8. What is the difference between normalization and


standardization?

Answer:

 Normalization (MinMaxScaler): Scales data to [0, 1].

 Standardization (StandardScaler): Scales data to have mean =


0 and std = 1.
Standardization is better when the data has outliers or is not
bounded.

9. What is correlation and covariance?

Answer:

 Correlation: Measures direction and strength of linear


relationship (ranges from -1 to 1).

 Covariance: Measures whether two variables vary together


(positive or negative), but doesn’t indicate strength.

💰 Finance Domain Basics

10. What is time-series data?

Answer:
Time-series data is data collected over time at regular intervals (e.g., daily
stock prices). It has temporal order, which is important for forecasting.
It often shows trends, seasonality, and noise.

11. What features can be used to predict stock prices?

Answer:

 Historical price data (Open, High, Low, Close)

 Volume

 Moving averages (SMA, EMA)

 Volatility

 Sentiment (optional)
 Technical indicators (MACD, RSI)

📦 Case Scenario Sample Answer

❓You are given stock price data for 5 years. How will you build a
predictive model?

Answer:

1. Data Cleaning – Handle missing values, remove outliers.

2. Feature Engineering – Create features like moving averages, RSI,


etc.

3. Train-Test Split – Use time-based splitting to prevent leakage.

4. Scaling – Apply StandardScaler or MinMaxScaler.

5. Model Selection – Use regression models (like Linear Regression,


Random Forest, LSTM for deep learning).

6. Evaluation – Use MAE, RMSE, R².

7. Hyperparameter Tuning – Use GridSearchCV or


RandomizedSearchCV.

8. Validation – Use rolling or walk-forward validation for time-series.

🧩 What is Feature Encoding in Machine Learning?

Feature encoding is the process of converting categorical (non-


numeric) data into numeric format so that machine learning
algorithms can understand and process it.

🔍 Why is Feature Encoding Important?

Most machine learning models (like linear regression, decision trees, SVM,
neural networks, etc.) only work with numerical data.
But real-world data often includes text or category-based values like:

 Gender: "Male", "Female"

 City: "Mumbai", "Delhi", "Pune"

 Department: "HR", "Sales", "IT"

These values must be converted into numbers before feeding them


into a model — and that’s where encoding comes in.
🧠 Types of Feature Encoding:

1. 🔢 Label Encoding

 Converts each category into a unique number.

Example:

Gend Encode
er d

Male 0

Femal
1
e

📌 Use when:

 The categorical variable is ordinal (i.e., has an order, like Low,


Medium, High).

 Or for tree-based models that handle label encoding well.

2. 🎯 One-Hot Encoding

 Creates a binary column for each category.

 Useful for nominal (unordered) data.

Example:

Mumb Del Pun


City
ai hi e

Mumb
1 0 0
ai

Delhi 0 1 0

Pune 0 0 1

📌 Use when:

 The categories don’t have a natural order.

 You want to avoid the model thinking that category 2 > 1 > 0.

⚠️Important Notes:
 Choose the right encoding method based on:

o Type of algorithm

o Whether categories have an order or not

o Number of unique categories (too many one-hot columns can


cause dimensionality issues)

✅ Summary:

Encoding Type Use When... Output

Categories have
Label Encoding 0, 1, 2...
order

Categories have no Binary


One-Hot Encoding
order columns

🧠 General AI Questions

1. What is the difference between AI, Machine Learning, and Deep


Learning?

Answer:

 AI is the broad concept of machines being able to carry out tasks


smartly.

 Machine Learning is a subset of AI where machines learn from


data.

 Deep Learning is a further subset of ML using neural networks with


many layers to learn complex patterns.

2. What are some real-world applications of AI?

Answer:

 Chatbots and virtual assistants (NLP)


 Fraud detection in banking (anomaly detection)

 Recommendation systems (collaborative filtering)

 Self-driving cars (computer vision)

 Stock price prediction (time-series forecasting)

3. What are the types of AI?

Answer:

 Narrow AI – Performs a specific task (e.g., Alexa, Siri)

 General AI – Human-like cognitive abilities (still theoretical)

 Super AI – Beyond human capabilities (future concept)

⚙️Machine Learning Questions

4. What is the difference between classification and regression?

Answer:

 Classification predicts a category/label (e.g., spam or not spam).

 Regression predicts a continuous value (e.g., house price).

5. What is cross-validation and why is it used?

Answer:
Cross-validation splits data into multiple train-test folds to evaluate model
performance more reliably, reducing the risk of overfitting to one specific
split.

6. What is regularization?

Answer:
Regularization adds a penalty to model complexity to avoid overfitting.

 L1 (Lasso): Can reduce some weights to zero (feature selection)

 L2 (Ridge): Penalizes large weights


7. What is the difference between accuracy, precision, recall, and
F1-score?

Answer:

Metric What It Measures

Accurac
Overall correct predictions
y

Precisio Correct positives out of all predicted


n positives

Correct positives out of all actual


Recall
positives

F1-
Harmonic mean of precision and recall
Score

📌 Use F1-Score when you have imbalanced datasets.

8. How does Gradient Descent work?

Answer:
It’s an optimization algorithm that adjusts model parameters (like
weights) by moving in the direction of the steepest descent of the
loss function — until it finds a minimum.

9. What is an epoch, batch size, and iteration in training models?

Answer:

 Epoch: One full pass through the entire dataset

 Batch Size: Number of samples processed before model updates

 Iteration: Number of batches in one epoch (iterations = data size /


batch size)

10. Difference between batch gradient descent, stochastic, and


mini-batch?

Answer:

 Batch: Uses whole dataset — stable but slow

 Stochastic: One sample at a time — faster but noisy


 Mini-batch: Small batches — balance of speed and stability

🧠 Deep Learning / Neural Networks (Optional)

11. What is a neural network?

Answer:
A neural network mimics the human brain with layers of nodes
(neurons) that learn to detect patterns in data.
It consists of input layer, hidden layers, and an output layer.

12. What is backpropagation?

Answer:
It’s the process where the model adjusts weights by calculating the
gradient of the loss function and updating the weights through
gradient descent.

13. What are activation functions and why are they important?

Answer:
Activation functions introduce non-linearity into the network so it can
learn complex patterns.
Examples: ReLU, Sigmoid, Tanh, Softmax.

📦 Model Deployment / Real-World Thinking

14. What steps are involved in building a machine learning


model?

Answer:

1. Data collection

2. Data cleaning and preprocessing

3. Feature engineering

4. Splitting into train/test sets

5. Model selection and training


6. Evaluation

7. Hyperparameter tuning

8. Deployment

9. Monitoring

15. What are some challenges in ML projects?

Answer:

 Poor or imbalanced data

 Overfitting

 Feature selection

 Model drift over time

 Interpretability

 Scalability

🤖 Artificial Intelligence Interview Questions & Answers

1. What is Artificial Intelligence?

Answer:
Artificial Intelligence (AI) is the simulation of human intelligence by
machines. It enables systems to think, learn, and make decisions like
humans.
It includes areas like machine learning, natural language processing,
computer vision, and robotics.

2. What are the main types of AI?

Answer:

 Narrow AI: Performs a specific task (e.g., voice assistants, spam


filters)

 General AI: Human-level intelligence (not achieved yet)

 Super AI: Surpasses human intelligence (hypothetical)


3. What is the difference between AI and ML?

Answer:

 AI is the broader concept of machines doing smart tasks.

 ML is a subset of AI where machines learn from data without being


explicitly programmed.

📌 In simple terms:

"ML is how AI learns."

4. What are the major branches of AI?

Answer:

 Machine Learning

 Deep Learning

 Natural Language Processing (NLP)

 Computer Vision

 Robotics

 Expert Systems

5. What are some real-life applications of AI?

Answer:

 Healthcare: Disease prediction, diagnosis, drug discovery

 Finance: Fraud detection, algorithmic trading

 Retail: Recommendation systems, inventory management

 Transportation: Self-driving cars, route optimization

 Customer Service: Chatbots, sentiment analysis

6. What is the Turing Test?

Answer:
The Turing Test, proposed by Alan Turing, tests a machine's ability to
exhibit intelligent behavior indistinguishable from a human.
If a human can’t tell whether they’re interacting with a machine or a
person, the machine is said to have passed the test.
7. What are the key components of an AI system?

Answer:

 Learning (acquiring knowledge)

 Reasoning (solving problems)

 Problem Solving

 Perception (processing sensory input)

 Language Understanding (like NLP)

8. What is the difference between weak AI and strong AI?

Answer:

 Weak AI (Narrow AI): Focused on a specific task (e.g., Google


Translate, Siri)

 Strong AI (General AI): Has human-like cognitive abilities — still a


theoretical concept.

9. What is the role of AI in financial markets?

Answer:

 Predicting stock prices and market trends

 Detecting fraud or anomalies

 Automating trading decisions (algorithmic trading)

 Risk modeling and credit scoring

10. What is Natural Language Processing (NLP)?

Answer:
NLP is a branch of AI that deals with the interaction between humans
and computers using natural language.
Examples include: speech recognition, sentiment analysis, chatbots, and
language translation.
11. What is the difference between rule-based AI and learning-
based AI?

Answer:

 Rule-Based AI: Uses predefined rules to make decisions (e.g., "if-


else" conditions).

 Learning-Based AI: Learns from data and improves over time


(e.g., ML models).

12. What are ethical concerns in AI?

Answer:

 Bias in data or algorithms

 Loss of jobs due to automation

 Privacy concerns

 Lack of transparency in decision-making

 Autonomous weapon systems

13. What is reinforcement learning?

Answer:
Reinforcement Learning (RL) is a type of ML where an agent learns by
interacting with an environment — it takes actions and receives
rewards or penalties.
Goal: Maximize cumulative reward.

14. What is computer vision?

Answer:
Computer vision is an AI field that enables machines to understand and
interpret visual data (images and videos).
Used in:

 Facial recognition

 Object detection

 Medical image analysis

 Self-driving cars
15. What are the challenges in AI?

Answer:

 Data quality and availability

 Bias in training data

 Interpretability of models

 Computational cost

 Ethical and legal issues

📝 Bonus: How to Answer AI Case Questions

If they ask:

“How would you use AI to detect fraud in financial transactions?”

Structure your answer:

1. Understand the problem – What does fraud look like?

2. Collect data – Historical transaction records (features like amount,


time, location).

3. Preprocess – Clean data, deal with class imbalance.

4. Model – Use classification models (Random Forest, XGBoost).

5. Evaluate – Use precision/recall (false positives matter).

6. Deploy – Monitor for model drift and update regularly.

You might also like