nova / machine_learning.txt
crazysanthosh's picture
Upload 25 files
7fde9b9 verified
Raw History Blame Contribute Delete
7.11 kB
## Machine Learning Fundamentals
Definition: Machine Learning is a subset of AI that enables systems to learn from data and improve their performance without being explicitly programmed.
Explanation: ML algorithms find patterns in data. Types: Supervised Learning (labeled training data β€” classification, regression), Unsupervised Learning (unlabeled data β€” clustering, dimensionality reduction), Reinforcement Learning (agent learns via rewards and penalties). The ML pipeline: collect data β†’ preprocess β†’ feature engineering β†’ model selection β†’ training β†’ evaluation β†’ deployment.
Example: Training a model to predict house prices based on square footage, location, and number of bedrooms.
Code Example:
```python
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import numpy as np
# Sample data
X = np.array([[1200, 3], [1500, 4], [900, 2], [2000, 5]]) # [sqft, rooms]
y = np.array([250000, 320000, 180000, 450000]) # prices
# Split into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# Train model
model = LinearRegression()
model.fit(X_train, y_train)
# Evaluate
predictions = model.predict(X_test)
mse = mean_squared_error(y_test, predictions)
print(f"MSE: {mse}, RMSE: {np.sqrt(mse)}")
```
Best Practices: Always split data into train/validation/test sets. Normalize features before training. Evaluate using cross-validation, not just a single train-test split.
Common Errors: Data leakage (using test data info during training). Not scaling features β€” distance-based algorithms suffer. Overfitting β€” model memorizes training data but fails on new data.
Interview Questions: Explain bias-variance tradeoff. What is overfitting and how do you prevent it? What is cross-validation?
## Neural Networks
Definition: Neural networks are computational models inspired by the brain, consisting of layers of interconnected nodes (neurons) that learn to map inputs to outputs.
Explanation: A neural network has an input layer, hidden layers, and an output layer. Each connection has a weight. Forward propagation computes predictions. Backpropagation computes gradients. Gradient descent updates weights to minimize loss. Activation functions (ReLU, Sigmoid, Softmax) introduce non-linearity, enabling the network to learn complex patterns.
Example: A simple network for classifying handwritten digits (MNIST).
Code Example:
```python
import tensorflow as tf
# Build a simple neural network
model = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)), # Input layer
tf.keras.layers.Dense(128, activation='relu'), # Hidden layer
tf.keras.layers.Dropout(0.2), # Regularization
tf.keras.layers.Dense(10, activation='softmax') # Output (10 classes)
])
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# Train
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0 # Normalize
model.fit(x_train, y_train, epochs=5, validation_split=0.1)
model.evaluate(x_test, y_test)
```
Best Practices: Use Dropout to prevent overfitting. Normalize input data. Use batch normalization for deeper networks. Monitor training with validation loss, not just training loss.
Common Errors: Forgetting to normalize inputs. Using Sigmoid in hidden layers (causes vanishing gradients β€” use ReLU). Not shuffling training data between epochs.
Interview Questions: Explain backpropagation. What is the vanishing gradient problem? What is the difference between batch, mini-batch, and stochastic gradient descent?
## Natural Language Processing (NLP)
Definition: NLP is the field of AI that enables computers to understand, interpret, and generate human language.
Explanation: NLP tasks include: Text classification, Sentiment analysis, Named Entity Recognition (NER), Machine Translation, Question Answering, Text summarization, and Language generation. Key techniques: tokenization, stemming, lemmatization, TF-IDF, word embeddings (Word2Vec, GloVe), and transformer models (BERT, GPT). Modern NLP uses Large Language Models (LLMs) trained on massive corpora.
Example: Sentiment analysis of product reviews β€” classify as positive, negative, or neutral.
Code Example:
```python
from transformers import pipeline
# Zero-shot text classification with BERT
classifier = pipeline("sentiment-analysis")
reviews = [
"This product is absolutely amazing! Highly recommend.",
"Terrible quality. Broke after one week.",
"It's okay, nothing special."
]
results = classifier(reviews)
for review, result in zip(reviews, results):
print(f"{result['label']} ({result['score']:.2f}): {review[:50]}")
```
Best Practices: Use pre-trained transformer models for most NLP tasks. Fine-tune on domain-specific data rather than training from scratch. Evaluate models with task-appropriate metrics (F1 for classification, BLEU for translation).
Common Errors: Not preprocessing text (lowercasing, removing noise). Using accuracy for imbalanced datasets (use F1/precision/recall). Treating all tokens equally β€” context matters (use embeddings).
Interview Questions: What is the transformer architecture? Explain attention mechanism. What is BERT and how does it differ from GPT?
## Large Language Models (LLMs)
Definition: LLMs are massive neural networks trained on vast amounts of text data that can understand and generate human language across diverse tasks.
Explanation: LLMs like GPT-4, Claude, Gemini, and LLaMA are based on the transformer architecture with billions of parameters. They are trained via next-token prediction (self-supervised) on web-scale data. Fine-tuning with RLHF (Reinforcement Learning from Human Feedback) aligns them with human preferences. Key concepts: temperature (randomness), context window (max tokens), prompting, RAG (Retrieval-Augmented Generation).
Example: Using an LLM API for code generation, summarization, and Q&A.
Code Example:
```python
from openai import OpenAI
client = OpenAI()
# Chat completion
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful coding expert."},
{"role": "user", "content": "Explain async/await in Python in 3 sentences."}
],
temperature=0.7, # 0 = deterministic, 1 = creative
max_tokens=200
)
print(response.choices[0].message.content)
```
Best Practices: Write clear, specific prompts (prompt engineering matters). Use RAG to ground LLMs in your proprietary data. Set temperature low for factual tasks, higher for creative tasks. Monitor for hallucinations.
Common Errors: Trusting LLM output without verification (hallucinations are real). Sending sensitive data to external APIs. Not chunking documents properly for RAG. Ignoring rate limits and token costs.
Interview Questions: What is RLHF? Explain RAG and when to use it. How do you handle LLM hallucinations in production?