Fixed Top Ad (Local Preview)800x50 โข Slot 6608427872
ML Concepts
1. Introduction to Machine Learning
- Machine learning is a branch of artificial intelligence in which computers learn patterns from data and use those patterns to make predictions or decisions. Instead of programming every decision rule manually, we provide: data, examples, desired outcomes, when available. The model learns a pattern that can be applied to new data. ๐ Machine learning uses past data to learn patterns that may be useful for future predictions.
- Rule-Based Approach: In rule-based programming, a person defines the rules.
Example:
If age < 18, provide a discount.Otherwise, do not provide a discount.The computer follows the rule exactly. Machine-Learning Approach: In machine learning, we provide historical examples. Example: customer age, purchase history, membership status, discount offered. The model learns patterns from these examples and predicts a suitable discount for a new customer. ๐ Rule-based systems follow predefined instructions. Machine-learning systems learn patterns from examples. - Machine learning may be useful when: the rules are difficult to write manually, large amounts of historical data are available, patterns are too complex for simple rules, predictions must be made for new observations, the underlying patterns may change over time. Examples: predicting house prices, detecting spam emails, predicting customer churn, grouping similar customers, recommending products, detecting unusual transactions.
- The three main learning types introduced in this lesson are: supervised learning, unsupervised learning, reinforcement learning.
1.1 ๐ค What is Machine Learning?
1.2 Rule-Based Programming vs. Machine Learning
1.3 When is Machine Learning Useful?
1.4 Main Types of Machine Learning
2. Supervised Learning
- In supervised learning, a model learns from labeled data.
Labeled data contains: input variables, the correct output.
We provide:
X = Features or inputsy = Label or outputThe model learns a relationship between X and y. Scikit-learn organizes supervised-learning methods into areas such as linear models, support vector machines, nearest neighbors, decision trees, and ensemble methods. - House-Price Prediction: Features: house size, location, number of rooms, age of the property. Label: house price. Spam Detection: Features: email content, sender information, number of links, email metadata. Label: spam or not spam. ๐ In supervised learning, the model learns using examples where the correct output is already known.
- Examples include: Linear Regression, Logistic Regression, K-Nearest Neighbors, Support Vector Machines, Decision Trees, Random Forests. Many algorithms can support more than one task. For example, nearest-neighbor, decision-tree, and support-vector methods can be used for classification or regression depending on the selected estimator.
- Supervised learning commonly includes two prediction tasks: regression, classification.
2.1 ๐ฏ What is Supervised Learning?
2.2 Supervised-Learning Examples
2.3 Common Supervised-Learning Algorithms
2.4 Main Supervised-Learning Tasks
3. Regression
- Regression is a supervised-learning task used to predict a numeric value. The output is usually a continuous number. Examples: house price, salary, temperature, sales amount, delivery time, electricity consumption. ๐ Regression answers questions such as "how much?" or "what numeric value?"
- Suppose we have employee data:
3.1 ๐ What is Regression?
3.2 Regression Example
Regression Example
| Academic Qualification | Experience | Company | Position | Salary |
|---|---|---|---|---|
| Bachelor's | 5 | Developer | 100,000 | |
| Master's | 8 | Microsoft | Data Engineer | 150,000 |
| Master's | 2 | Developer | 80,000 | |
| Bachelor's | 1 | Developer | ? |
- Features: academic qualification, experience, company, position. Label: salary. The task is to predict the salary of the final employee.
- Examples include: Linear Regression, K-Nearest Neighbors Regression, Decision Tree Regression, Random Forest Regression, Support Vector Regression.
3.2 Regression Example (continued)
3.3 Common Regression Algorithms
4. Classification
- Classification is a supervised-learning task used to predict a category or class label. Examples: spam or not spam, disease or no disease, customer will leave or stay, transaction is fraudulent or legitimate, product category. ๐ Classification answers questions such as "which category?" or "which class?"
- Suppose we have health data:
4.1 ๐ท๏ธ What is Classification?
4.2 Classification Example
Classification Example
| Age | Blood Pressure | Cholesterol | Diabetes |
|---|---|---|---|
| 25 | 120 | 200 | No |
| 45 | 140 | 250 | Yes |
| 30 | 130 | 220 | No |
| 50 | 150 | 300 | ? |
- Features: age, blood pressure, cholesterol level. Label: diabetes status. The task is to predict whether the final patient belongs to the Yes or No class.
- Binary Classification: The output contains two possible classes. Examples: spam or not spam, disease or no disease, yes or no. Multiclass Classification: The output contains more than two possible classes. Examples: low, medium, or high risk; setosa, versicolor, or virginica; bronze, silver, or gold membership.
- Examples include: Logistic Regression, K-Nearest Neighbors, Support Vector Machines, Decision Trees, Random Forests, Naive Bayes. ๐ Despite its name, Logistic Regression is mainly used for classification.
4.2 Classification Example (continued)
4.3 Binary and Multiclass Classification
4.4 Common Classification Algorithms
5. Regression vs. Classification
- A quick comparison of the two tasks:
5.1 Quick Comparison
Quick Comparison
| Task | Output Type | Example |
|---|---|---|
| Regression | Numeric value | Predict salary |
| Classification | Category or class | Predict diabetes status |
- Ask:
What am I trying to predict?If the answer is a numeric value:RegressionIf the answer is a category:Classification๐ The target variable usually determines whether the problem is regression or classification.
5.2 How to Identify the Task
6. Unsupervised Learning
- In unsupervised learning, a model works with unlabeled data.
We provide features:
X = Input variablesWe do not provide a known label:No y value is providedThe model attempts to discover structure or patterns in the data. - Unsupervised learning can be used to: group similar observations, reduce the number of variables, discover hidden structures, find associations, support exploratory analysis.
- Suppose we have: customer age, number of purchases, average spending, visit frequency. We do not have predefined customer segments. A clustering algorithm may identify groups such as: frequent high-value customers, occasional customers, low-spending customers. ๐ The algorithm discovers groups from similarities in the available features.
- Examples include: K-Means Clustering, Hierarchical Clustering, DBSCAN, Principal Component Analysis, Association Rule Learning. Scikit-learn provides unsupervised methods for tasks including clustering, dimensionality reduction, nearest-neighbor analysis, and related pattern-discovery problems.
- Clustering: Clustering groups similar observations. Examples: customer segmentation, document grouping, product grouping. Dimensionality Reduction: Dimensionality reduction reduces the number of variables while preserving useful information. Example: reducing 50 related features into a smaller number of components. Principal Component Analysis, or PCA, is a common dimensionality-reduction technique.
6.1 ๐ What is Unsupervised Learning?
6.2 Unsupervised-Learning Goals
6.3 Example: Customer Segmentation
6.4 Common Unsupervised-Learning Algorithms
6.5 Clustering and Dimensionality Reduction
7. Reinforcement Learning
- In reinforcement learning, an agent learns by interacting with an environment. The agent: observes the current situation, chooses an action, receives a reward or penalty, updates its decision strategy, repeats the process. The goal is to learn a strategy that maximizes cumulative reward.
- Agent: The learner or decision-maker. Environment: The world in which the agent acts. State: The current situation observed by the agent. Action: A decision made by the agent. Reward: Feedback received after an action. Policy: The agent's strategy for choosing actions.
- Robot Navigation: reward for reaching the exit, penalty for collisions, goal: learn an effective path. Game Playing: reward for winning, penalty for losing, goal: learn actions that improve long-term performance. ๐ Reinforcement learning learns from interaction and feedback rather than from fixed labeled examples.
7.1 ๐ฎ What is Reinforcement Learning?
7.2 Important Reinforcement-Learning Terms
7.3 Reinforcement-Learning Examples
8. Comparing the Main Learning Types
- A comparison of the three main learning types:
8.1 Quick Comparison
Comparing the Main Learning Types
| Learning Type | Data Provided | Main Goal | Example |
|---|---|---|---|
| Supervised | Features and labels | Predict an output | Predict house price |
| Unsupervised | Features without labels | Discover patterns | Group customers |
| Reinforcement | Interaction and rewards | Learn a decision strategy | Train a game agent |
- Ask:
Do I have known outputs for past observations? Consider:
Supervised learningDo I only have features and want to discover patterns? Consider:Unsupervised learningDoes an agent need to learn through actions and rewards? Consider:Reinforcement learning
8.2 Selection Questions
9. Important Machine-Learning Terms
- A feature is an input variable used by a model.
Examples: age, income, house size, number of rooms.
Features are commonly represented using:
X - The label, also called the target, is the output that a supervised model tries to predict.
Examples: house price, diabetes status, customer churn, salary.
The label is commonly represented using:
y๐ Features are the inputs. The label is the desired output. - An observation is one row or individual example in a dataset. Example: one customer, one house, one patient, one transaction.
- A model is a learned mathematical representation of patterns in data.
It receives features and produces an output.
Features โ Model โ Prediction - Training is the process in which a model learns patterns from training data. During training, the model adjusts its internal parameters to improve its predictions.
- A prediction is the output produced by a trained model for an input.
Example:
Predicted salary = 75,000Predicted class = Diabetes - Evaluation is the process of measuring how well a trained model performs. The model should be evaluated using data that was not used to fit it. Model evaluation measures prediction quality on unseen data and includes different metrics for classification, regression, and clustering.
- A parameter is a value learned by the model during training.
Example:
Coefficients learned by Linear Regression - A hyperparameter is a setting chosen before or during the model-development process rather than learned directly from the training data.
Examples:
Number of neighbors in KNNMaximum depth of a Decision TreeNumber of clusters in K-MeansHyperparameter tuning is part of model selection and evaluation workflows.
9.1 ๐งฉ Feature
9.2 Label or Target
9.3 Observation
9.4 Model
9.5 Training
9.6 Prediction
9.7 Evaluation
9.8 Parameter
9.9 Hyperparameter
10. Training and Testing Data
- If we evaluate a model using the same data it learned from, the result may be overly optimistic. We therefore commonly divide the data into: training data, testing data.
- The training set is used to fit the model.
Model learns from training data - The testing set is used to evaluate how well the trained model performs on unseen observations.
Model is evaluated on testing data๐ Training data teaches the model. Testing data checks whether the model generalizes. - A validation set may be used to: compare different models, choose hyperparameters, make development decisions.
A simple conceptual split is:
Training set โ Learn the modelValidation set โ Choose settingsTesting set โ Final evaluationCross-validation and hyperparameter tuning are standard parts of model selection and evaluation.
10.1 ๐งช Why Split the Data?
10.2 Training Set
10.3 Testing Set
10.4 Validation Data
11. Underfitting and Overfitting
- Underfitting occurs when a model is too simple to capture the important patterns in the data. It usually performs poorly on: training data, testing data. Example: Using a straight line to represent a strongly curved relationship. ๐ Underfitting is commonly associated with high bias.
- Overfitting occurs when a model learns the training data too closely, including noise or unimportant details. It may perform: very well on training data, poorly on unseen data. ๐ Overfitting means the model memorizes training details but does not generalize well.
- A balanced model captures meaningful patterns without learning unnecessary noise. The goal is not simply to achieve the best training performance. The goal is to perform well on new, unseen data.
- Bias: Bias is error caused by assumptions that are too simple. High bias is often associated with underfitting. Variance: Variance describes how sensitive a model is to changes in its training data. High variance is often associated with overfitting. Bias-Variance Tradeoff: The bias-variance tradeoff describes the balance between: a model that is too simple, a model that is too sensitive to training data. ๐ A useful model balances learning enough structure without memorizing noise.
11.1 ๐ What is Underfitting?
11.2 ๐ What is Overfitting?
11.3 Balanced Model
11.4 Bias and Variance
12. Data Preparation for Machine Learning
- Before training a model, we may need to handle: missing values, duplicate rows, incorrect data types, inconsistent categories, outliers, invalid values.
- Many machine-learning algorithms require numeric input.
Categorical values may need to be converted into numbers.
Example:
City = Kathmandu, Pokhara, Biratnagarmay be encoded into numeric columns. This process is called:Encoding - Feature scaling places numeric variables on comparable scales.
Example:
Age: 18 to 80Salary: 20,000 to 500,000Some algorithms may be heavily influenced by the larger numeric scale. Common scaling approaches include: standardization, normalization. ๐ Scaling is important for some algorithms, but not every algorithm requires it. - Data leakage occurs when information unavailable at prediction time improperly influences model training or evaluation. A common prevention rule is: split the data before learning preprocessing values from it. For example, a scaler should learn its values from the training data and then apply the same transformation to validation and testing data. Pipelines can organize preprocessing and modeling into a consistent workflow.
12.1 ๐งน Clean the Data
12.2 Feature Encoding
12.3 Feature Scaling
12.4 Avoiding Data Leakage
13. Model Evaluation
- Model evaluation checks whether a model performs well on unseen data. A model that performs well only on its training data may not be useful in practice. Scikit-learn provides separate metric families for classification, regression, clustering, and other model types.
- Common classification metrics include: accuracy, precision, recall, F1-score, confusion matrix, ROC-AUC.
- Common regression metrics include: Mean Absolute Error, Mean Squared Error, Root Mean Squared Error, Rยฒ score. ๐ The correct evaluation metric depends on the task and the real-world cost of different errors.
13.1 ๐ Why Evaluate a Model?
13.2 Classification Metrics
13.3 Regression Metrics
14. Steps for Solving Machine-Learning Problems
- Clearly identify: the prediction or discovery goal, the target variable, if one exists, the type of machine-learning task, how success will be measured.
- Determine: what each row represents, what each column represents, where the data came from, whether the data represents the real problem.
- Check for: missing values, duplicates, outliers, incorrect types, inconsistent values, unbalanced classes.
- For supervised learning:
X = df[feature_columns]y = df[target_column]For unsupervised learning:X = df[feature_columns] - Create separate datasets for training and evaluation. Example: training data, testing data. Validation or cross-validation may also be used during model development.
- Possible steps include: filling missing values, encoding categorical variables, scaling numeric variables, selecting useful features. Preprocessing should be learned using the training data.
- Select an algorithm appropriate for the task.
Examples:
Regression โ Linear RegressionClassification โ Logistic RegressionClustering โ K-MeansTrain the model using the training data. - Evaluate the model using suitable metrics and data that was not used to fit it. Compare multiple models when appropriate.
- Possible improvements include: better data cleaning, more useful features, different algorithms, hyperparameter tuning, cross-validation, addressing underfitting or overfitting. These are standard areas within model selection and evaluation.
- After evaluation, an appropriate model may be deployed for real use. Monitoring may check whether: prediction quality changes, input data changes, errors increase, retraining becomes necessary. ๐ Machine learning is an iterative process. Evaluation and improvement may occur repeatedly.
14.1 Define the Problem
14.2 Collect and Understand the Data
14.3 Explore and Clean the Data
14.4 Separate Features and Target
14.5 Split the Data
14.6 Preprocess the Features
14.7 Choose and Train a Model
14.8 Evaluate the Model
14.9 Improve the Model
14.10 Deploy and Monitor
15. Final Machine-Learning Summary
Final Machine-Learning Summary
| Concept | Meaning |
|---|---|
| Supervised learning | Learns from features and known labels |
| Regression | Predicts a numeric value |
| Classification | Predicts a category |
| Unsupervised learning | Finds patterns without known labels |
| Reinforcement learning | Learns through actions and rewards |
| Feature | Input used by a model |
| Label | Output a supervised model predicts |
| Training | Process of learning from data |
| Evaluation | Measuring performance on unseen data |
| Underfitting | Model is too simple |
| Overfitting | Model learns training details too closely |
| Generalization | Ability to perform well on new data |
- The goal of machine learning is not merely to fit past data. It is to learn patterns that remain useful when the model encounters new data.
๐ Note