1. How do you implement a basic linear regression model from scratch in Python?
python
CopyEdit
import numpy as np
def linear_regression(X, y, lr=0.01, epochs=1000):
m, n = [Link]
X = np.c_[[Link](m), X] # Add bias term
theta = [Link](n + 1)
for _ in range(epochs):
predictions = [Link](theta)
gradient = (1/m) * [Link](predictions - y)
theta -= lr * gradient
return theta
# Example usage
X = [Link]([[1], [2], [3]])
y = [Link]([2, 4, 6])
print(linear_regression(X, y))
2. Write a function to calculate the F1-score from a confusion matrix.
python
CopyEdit
def f1_score(tp, fp, fn):
precision = tp / (tp + fp) if (tp + fp) else 0
recall = tp / (tp + fn) if (tp + fn) else 0
return 2 * (precision * recall) / (precision + recall) if (precision + recall) else 0
print(f1_score(30, 10, 5)) # Example
3. How do you balance an imbalanced dataset in Python?
python
CopyEdit
from imblearn.over_sampling import SMOTE
X_resampled, y_resampled = SMOTE().fit_resample(X, y)
4. Write a function to tokenize text and remove stopwords using NLTK.
python
CopyEdit
from [Link] import word_tokenize
from [Link] import stopwords
import nltk
[Link]('punkt')
[Link]('stopwords')
def clean_text(text):
tokens = word_tokenize([Link]())
return [word for word in tokens if [Link]() and word not in [Link]('english')]
print(clean_text("This is a sample text with stopwords."))
5. Write a FastAPI endpoint to deploy a trained AI model.
python
CopyEdit
from fastapi import FastAPI
import pickle
import numpy as np
app = FastAPI()
model = [Link](open("[Link]", "rb"))
@[Link]("/predict/")
def predict(features: list):
prediction = [Link]([Link](features).reshape(1, -1))
return {"prediction": [Link]()}
# Run: uvicorn filename:app --reload
2. Scenario-Based ML Questions
6. Your deep learning model is overfitting. What steps do you take?
o Use dropout layers
o Apply L1/L2 regularization
o Increase training data
o Use data augmentation
o Reduce model complexity
7. Your NLP model generates incorrect entities in Named Entity Recognition (NER). What do
you do?
o Fine-tune with a domain-specific dataset
o Use a better tokenization approach
o Try different embedding models like BERT
8. Your AI API is slow. How do you optimize it?
o Convert model to TensorRT
o Use batch inference instead of real-time
o Deploy using a microservices architecture
9. A deployed AI model's accuracy is dropping over time. Why?
o Model drift due to data changes
o Bias in new incoming data
o Outdated training data
o Fix by retraining on updated data
10. Your ML model performs well on test data but fails in production. Possible reasons?
Data leakage
Feature distribution change
Model trained on different environment than production
3. Debugging and Optimization Questions
11. How do you debug a NaN loss in a deep learning model?
Check for exploding gradients
Reduce learning rate
Clip gradients
Ensure proper data normalization
12. Your gradient boosting model is taking too long to train. How do you speed it up?
Reduce max_depth
Use early stopping
Subsample data (subsample in XGBoost)
13. How do you interpret a deep learning model's decisions?
Use SHAP values
Apply Grad-CAM for CNNs
Use LIME for explainability
14. Your chatbot often generates irrelevant responses. What could be wrong?
Poor training data quality
Weak prompt engineering
Lack of fine-tuning
15. Your recommendation system is biased. How do you fix it?
Use fairness-aware training methods
Balance dataset across user groups
Regularly monitor for biased outcomes
4. Data Engineering & SQL Questions
16. Write an SQL query to find users who made more than 10 transactions in a month.
sql
CopyEdit
SELECT user_id, COUNT(*) AS transactions
FROM transactions
WHERE transaction_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)
GROUP BY user_id
HAVING transactions > 10;
17. How do you store and retrieve embeddings efficiently?
Use FAISS or Pinecone for similarity search
Store embeddings in a NoSQL database (e.g., MongoDB)
18. What are the best practices for handling large datasets in Python?
Use pandas.read_csv(chunksize=10000)
Store data in Apache Parquet format
Use Dask for parallel processing
19. How do you perform efficient feature selection?
Use Mutual Information
Apply Recursive Feature Elimination (RFE)
Train with Lasso (L1 regularization)
20. How do you ensure data privacy when using AI models?
Use Differential Privacy
Remove personally identifiable information (PII)
5. Deployment and MLOps Questions
21. How do you monitor AI models in production?
Track model performance (latency, accuracy)
Use Prometheus & Grafana for monitoring
22. How do you reduce inference time in a deep learning model?
Use model quantization (e.g., TensorRT, ONNX)
Prune unnecessary layers
23. Explain how you would deploy an AI model in AWS.
Train model → Save as .pkl → Deploy via AWS SageMaker or Lambda
24. How do you scale an AI model for high traffic?
Use Kubernetes with auto-scaling
Deploy multiple instances behind a load balancer
25. How do you prevent model drift in production?
Continuously retrain model with new data
Monitor input feature distributions
6. Coding Challenges
26. Write Python code to generate word embeddings using Word2Vec.
python
CopyEdit
from [Link] import Word2Vec
sentences = [["AI", "is", "transforming", "the", "world"], ["Machine", "learning", "is", "exciting"]]
model = Word2Vec(sentences, vector_size=10, window=2, min_count=1, workers=4)
print([Link]["AI"]) # Get vector for "AI"
27. Write a function to check if a dataset has missing values.
python
CopyEdit
import pandas as pd
def check_missing_values(df):
return [Link]().sum()
df = [Link]({"A": [1, None, 3], "B": [4, 5, None]})
print(check_missing_values(df))
28. Implement cosine similarity between two vectors.
python
CopyEdit
from numpy import dot
from [Link] import norm
def cosine_similarity(a, b):
return dot(a, b) / (norm(a) * norm(b))
print(cosine_similarity([1, 2, 3], [4, 5, 6]))