ML Revision
ML Revision
#Given:
Examples:
● Electronic medical records: Each record can be considered a data point, with features
like age, symptoms, and test results, and a label like diagnosis or treatment.
#Find:
● Predictive function (f(x)): This function takes an input feature vector (x) and predicts a
corresponding output (y). This is commonly used in supervised learning tasks like
classification or regression.
● Modeling function (h(x)): This function models the underlying distribution of the data.
It can be used to generate new data points similar to the existing ones (e.g., generative
models).
● Conditional generative function (g(z|x) or g(z|y)): This function generates new data
points or labels conditioned on latent variables (z) or input features (x). This is
commonly used in generative models like GANs and VAEs.
● Diagnosis or treatment regimen: This is a specific application of machine learning,
where the goal is to use the learned models to predict a diagnosis or recommend a
treatment plan for a patient based on their medical records.
Principle about data quality and quantity: High-quality and sufficient quantities of
data are crucial for training effective ML models.___________
a. Data types and structure:
b. Process:
Principle about iterative improvement (cải tiến lặp đi lặp lại): Machine learning is an
iterative process involving continuous refinement (tinh chỉnh liên tục).
Principle about training and optimization: Learning process involves optimizing a loss
function to minimize prediction errors.
#Data transformation:
Key Components:
● Oligonucleotides: These are short, single-stranded DNA or RNA molecules. They serve
as the fundamental units of the data.
● Pairwise Similarity: This measures the degree of similarity between two
oligonucleotides. It's often calculated based on factors like sequence alignment, base
composition, or structural properties.
● Matrix Representation: A matrix is a rectangular array of numbers. In this case, each
row and column represents an oligonucleotide, and the values within the matrix
correspond to the pairwise similarity between the corresponding oligonucleotides.
c. Methods:
Principle about generalization (Nguyên tắc về khái quát hóa): A model’s ability to
perform well on unseen data is more important than its performance on training data.
Principle on feature engineering (Nguyên tắc về kỹ thuật tính năng): Transforming raw
data into features that better represent the underlying patterns can improve model
performance.
Principle about bias-variance tradeoff (Nguyên tắc về sự đánh đổi giữa độ lệch và
phương sai): The balance between bias (error due to overly simplistic models) and variance
(error due to overly complex models) must be managed carefully.
● Unlabeled data, on the other hand, only contains the data points themselves without
any associated labels. In the same image classification example, unlabeled data would
consist of images without their corresponding labels.
#####Types of machine learning:
● Supervised learning (Học có giám sát):The algorithm is trained on a dataset with
labeled inputs, allowing it to learn a mapping between inputs and outputs.
○ Examples:
■ Classification (Phân loại): Image classification (e.g., identifying cats vs.
dogs in images); Phát hiện sai sót (fraut detection); Phân biệt email spam
(spam detection); Chẩn đoán bệnh (diagnostics)
■ Regression (Hồi quy): Đánh giá rủi ro (risk assesment), Dự đoán giá (price
prediction) (e.g., predicting house prices)
● Unsupervised learning (Học không có giám sát): The algorithm is trained on a dataset
without labels, allowing it to discover patterns and relationships within the data.
○ Examples:
■ Clustering (Phân nhóm): Sinh học (biology)Grouping of plant and animal
species based on genetic characteristics.; Khách hàng (customer
grouping) (e.g., grouping similar customers); Nhóm doanh nghiệp
(enterprise )Grouping of businesses based on revenue, size, and field of
operation
■ Dimensionality reduction (Rút gọn số chiều): Khai khá văn bản(text
mining) (e.g., simplifying complex data); Nhận dạng mặt người (face
recognition); Hiển thị dữ liệu lớn (big data visualization); Nhận dạng ảnh
(image recognition)
● Reinforcement learning (Học tăng cường): The algorithm learns by interacting with an
environment and receiving rewards or penalties based on its actions.
○ Examples include Trò chơi (Gaming), Tài chính (finance sector), Chế tạo (
manufactoring), Quản lý hàng tồn kho (inventory management), Robot (Robot
navigation).
#kernel methods:
Kernel Methods are a powerful technique in machine learning, particularly utilized in models
like Support Vector Machines (SVMs). The primary objective of Kernel Methods is to address
non-linear data by transforming it into a higher-dimensional feature space where the data
becomes linearly separable, thus simplifying classification or regression tasks.
Kernel Method là một kỹ thuật quan trọng trong học máy, đặc biệt được sử dụng nhiều trong
các mô hình như Support Vector Machines (SVM). Mục đích chính của Kernel Method là xử lý
các dữ liệu không tuyến tính (non-linear data) bằng cách chuyển đổi chúng sang một không
gian có độ chiều cao hơn, nơi dữ liệu có thể trở nên tuyến tính và dễ dàng phân loại hơn.
When data cannot be easily classified or predicted in its original space (e.g., using linear
models), Kernel Methods facilitate the mapping of data into an alternative feature space where
linear models can be effectively applied. For instance, in a 2D space, data might not be linearly
separable using a straight line. However, by projecting the data into a 3D space, a plane can be
used to easily separate the classes.
#Probabilistic graphical models (mô hình đồ họa xác suất): A probabilistic graphical
model (graphical model) is a way of representing probabilistic relationships between random
variables (bring graph theory and probability theory in a powerful formalism for multivariate
statistical modeling)
#Ensemble learning: Ensemble methods employ multiple learners and combine their
predictions to achieve higher performance than that of a single learner.
• Boosting: Make examples currently misclassified more important
● Kỹ thuật này tạo ra nhiều mô hình bằng cách sử dụng các tập con khác nhau từ
dữ liệu huấn luyện (lấy mẫu lại với phép thay thế, tức là cùng một mẫu có thể
xuất hiện nhiều lần trong các tập con).
● Mỗi mô hình được huấn luyện độc lập, và kết quả dự đoán của các mô hình sẽ
được kết hợp lại (thường là bằng cách lấy trung bình đối với bài toán hồi quy
hoặc lấy đa số phiếu đối với bài toán phân loại).
● Mục đích Giảm phương sai (variance) của mô hình và cải thiện tính ổn định.
○ This technique creates multiple models by using different subsets of the
training data (sampling with replacement, meaning the same sample can
appear multiple times in different subsets). Each model is trained
independently, and the predictions of the models are combined (usually
by taking the average for regression problems or by majority voting for
classification problems).Purpose: To reduce the variance of the model
and improve stability.
• Bagging: Use different subsets of the training data for each model (Random Forest)
● Kỹ thuật này huấn luyện một chuỗi các mô hình, trong đó mỗi mô hình
mới cố gắng sửa các lỗi của mô hình trước đó.
● Boosting chú trọng vào các điểm dữ liệu bị phân loại sai hoặc có lỗi cao ở
các lần trước và gán trọng số lớn hơn cho chúng trong các lần huấn luyện
sau.
● Mục đích Giảm độ chệch (bias) của mô hình.
This technique trains a sequence of models, where each new model tries to
correct the errors of the previous models. Boosting focuses on the data points that were
misclassified or had high errors in previous iterations and assigns higher weights to
them in subsequent training rounds.Purpose: To reduce the bias of the model.
# Semi-supervised learning (Học Máy Bán Giám sát ): A class of machine learning
techniques that make use of both labeled and unlabeled data for training - typically a small
amount of labeled data with a large amount of unlabeled data.
Tại sao lại cần học bán giám sát? Trong nhiều trường hợp thực tế, việc thu thập dữ liệu
có nhãn là một quá trình tốn kém và mất thời gian. Trong khi đó, dữ liệu không nhãn lại rất dễ
thu thập. Học bán giám sát giúp chúng ta tận dụng tối đa lượng dữ liệu sẵn có, đặc biệt là khi
lượng dữ liệu có nhãn rất hạn chế.
How it works:
● Labeled data: Helps the model learn the relationships between features and labels.
● Unlabeled data: Helps the model learn the structure of the data, the probability
distribution of the data, and the underlying relationships between data points.
● Generative models: Sử dụng các mô hình sinh để mô hình hóa phân bố xác suất của dữ
liệu và tạo ra dữ liệu mới.
● Graph-based methods: Xây dựng đồ thị kết nối các điểm dữ liệu, sau đó sử dụng thông
tin từ đồ thị để truyền nhãn từ dữ liệu có nhãn sang dữ liệu không nhãn.
● Low-density separation: Các lớp khác nhau thường được phân tách bởi các vùng có mật
độ điểm dữ liệu thấp.
● Change of representation
● Maximizes data utilization: Improves model performance when labeled data is limited.
● Flexibility: Applicable to a wide range of problems.
#Model selection:
In machine learning (ML), a model is a mathematical function (parametric collection of
probability distributions) or algorithm that maps input data (features) to output data
(predictions or decisions).
1, Classification vs Prediction:
Examples:
Prediction: In prediction problems, the response variable is continuous. This means it can take
on any value within a given range.
Examples:
○ The known label of test object is compared with the classified result from the
model
○ Accuracy rate is the percentage of test set objects that are correctly classified by
the model
○ Test set is independent of training set, otherwise over-fitting will occur
(Overfitting occurs when the model becomes too complex and fits the training
data too closely, leading to poor performance on new, unseen data.)
● Predictive accuracy: the ability of the classifier to correctly predict unseen data
● Speed: refers to computation cost
● Robustness: the ability of the classifier to make correctly predictions given noisy data or
data with missing values
● Scalability: the ability to construct the classifier efficiently given large amounts of data
● Interpretability: the level of understanding and insight that is provided by the classifier
=> If many (thousands) of examples are available, including several hundred examples
from each class, we evaluate our classifier method by randomly split data into training and
test sets (usually 2/3 for train,1/3 for test). Build a classifier using the train set and
evaluate it using the test set.
2, The k-NN classifier:
● K-fold cross-validation:
○ First step: The dataset is divided into k equal-sized partitions (phân vùng).
○ Second step: The model is trained on k-1 partitions and evaluated on the
remaining partitions. This process is repeated k times, and the results are
averaged.
..stratified: phân tầng
● Classification Rule:
○ Find the nearest k neighbors to the record to be classified.
○ Use a majority decision rule to classify the record, where the record is
classified as a member of the majority class of the k neighbors
● Choosing Parameter k:
○ If k is too low, we may be fitting to the noise in the data
○ If k is too high, we will miss out local structure in the data (important)
○ Typically, fall in the range 1–20, often an odd number is chosen
○ Choose the k that minimizes error rates for various choices of k
● Weighted k-NN:
○ Each neighbor’s weight is determined by the inverse (nghịch đảo) of its
distance from the record to be predicted.
○ Given d1, d2, ... , dk distances to each of the k neighbors, the weight for
neighbor i is computed as
Where:
● P(H∣e): The posterior probability, or the probability of hypothesis H being true given
the data e.
● P(e∣H): The likelihood, or the probability of the data given the hypothesis.
● P(H): The prior probability, or the initial belief about the hypothesis before observing
the data.
● P(e): The marginal likelihood or the total probability of observing the data under all
possible hypotheses.
Maximum A Posteriori (MAP) and Maximum Likelihood Hypothesis (MLH) are two widely
used criteria in parameter estimation and machine learning for finding the most probable value
of a parameter in a statistical model. Both aim to maximize a probability function, but they
differ in their approaches.
● Core idea: MLH finds the value of the parameter that makes the observed data most
likely. In other words, it seeks the parameter that best "explains" the data.
Formula:
θ_ML = argmax_θ P(D|θ)
● Where:
○ θ: The parameter to be estimated
○ D: The observed data
○ P(D|θ): The probability of the data D given the parameter θ (likelihood function)
● Advantages:
○ Simple and intuitive.
○ Widely used in many statistical models.
● Disadvantages:
○ Can lead to overfitting when the data is noisy or the sample size is small.
○ Does not utilize prior information about the parameter.
● Core idea: MAP incorporates both the observed data and prior information about the
parameter to find the most probable value of the parameter. It treats the parameter θ as
a random variable and finds the value of θ that maximizes the posterior probability
P(θ|D).
Formula:
θ_MAP = argmax_θ P(θ|D) = argmax_θ P(D|θ)P(θ)
● Where:
○ P(θ): The prior probability of the parameter θ, representing prior knowledge
about the parameter.
● Advantages:
○ More flexible than MLH as it utilizes both data and prior information.
○ Can help reduce overfitting.
● Disadvantages:
○ The choice of prior distribution can influence the results.
○ More complex than MLH.
Example:
● The network structure (DAG) defines the relationships and conditional dependencies
between the variables. It shows which variables directly affect others.
● The CPTs provide the actual probabilities that quantify the strength of these
relationships.
These two components allow the Bayesian network to represent a complex joint probability
distribution in a compact form by factoring it into conditional probabilities.
#Benefits of Bayesian Belief Networks:
1. Data has a clear probabilistic distribution: Bayes' Theorem works well when the data
can be modeled using probability distributions, especially when you have prior
knowledge about the probabilities of the classes.
2. Classification problems with independent features: Naive Bayes, a popular variant of
Bayes' Theorem, assumes that the features of the data are independent, which
simplifies calculations. Although this assumption may not be entirely true, Naive Bayes
still performs well in many real-world datasets.
3. When a fast and efficient algorithm is needed for large datasets: Naive Bayes is very
fast because it only requires the computation of probabilities of features and classes,
making it scalable for large datasets.
4. Problems with imbalanced class distributions: Bayes' Theorem handles imbalanced
data well, where one class has significantly fewer examples than another. It allows the
integration of prior knowledge about the frequency of the classes.
5. Text classification or natural language processing problems: Naive Bayes is
commonly used in text classification, such as spam email detection or document topic
categorization, as it works well with discrete data and is scalable to large datasets.
Summary:
● Use K-NN when you have small datasets, lack prior knowledge of the distribution, and
don't need to make assumptions about the data.
● Use Bayes' Theorem when you can model the data probabilistically and need a fast
method, especially for imbalanced or large datasets
● Each internal node (nút nội bộ) denotes a test on an attribute (Ví dụ: "Tuổi > 30?", "Giới
tính = Nam?")
● Each branch (nhánh) represents an outcome of the test (Ví dụ: "Đúng" hoặc "Sai")
● Leaf nodes (nút lá) represent classes or class distributions (Ví dụ: "Mua hàng" hoặc
"Không mua hàng"). The process continues until all nodes are either leaf nodes or have
no more attributes to split on. Each leaf node represents a predicted value of the target
variable.
● The top-most node in a tree is the root node (nút gốc), which represents the entire
dataset.
Two steps: recursively (đệ quy) generate the tree(1-4), and prune the tree (5):
1. At each node, choose the “best” attribute by a given measure for attribute selection
2. Extend tree by adding new branch for each value of the attribute
4. If examples in a node belong to one class. Then Stop Else Repeat steps 1-4 for leaf nodes
#Entropy
● Entropy bằng 0: Khi tất cả các thành viên của tập dữ liệu S thuộc cùng một lớp, entropy
bằng 0. Điều này có nghĩa là the data is more pure or certain, there’s no uncertainty
● Entropy bằng 1: Khi tập dữ liệu chứa số lượng bằng nhau của các mẫu dương và âm,
entropy bằng 1. Đây là mức độ không chắc chắn cao nhất, vì không có thông tin đủ để
phân biệt các lớp.
● Entropy giữa 0 và 1: Nếu số lượng mẫu dương và âm không bằng nhau, entropy sẽ nằm
giữa 0 và 1. Càng gần 0, độ không chắc chắn càng thấp, và ngược lại, càng gần 1, độ
không chắc chắn càng cao.
We define a measure, called information gain (là một thước đo hiệu quả của một thuộc tính
trong việc phân loại dữ liệu. Nó đại diện cho sự giảm thiểu dự kiến của entropy khi chia dữ liệu
theo thuộc tính đó), of the effectiveness of an attribute in classifying data. It is the expected
reduction in entropy caused by partitioning the objects according to this attribute
Information Gain là hiệu số giữa entropy ban đầu và tổng entropy sau phân chia.
Nếu Information Gain cao, điều đó có nghĩa là thuộc tính A đã giúp giảm được độ không
chắc chắn của dữ liệu sau khi phân chia.
trong đó:
● SplitInfo(S, A) là một thước đo sự phân chia của thuộc tính A trên tập S. Nó càng
nhỏ khi thuộc tính A tạo ra các tập con có kích thước tương đối bằng nhau.
ID3 (Iterative Dichotomiser 3): là một thuật toán xây dựng cây quyết định dựa trên Information
Gain (lợi ích thông tin). Nó chọn thuộc tính có Information Gain cao nhất để chia dữ liệu thành
các nhóm nhỏ hơn.
● Information Gain đo lường sự giảm độ không chắc chắn (entropy) khi chia tập dữ
liệu dựa trên một thuộc tính. Thuộc tính nào giảm độ không chắc chắn nhiều
nhất sẽ được chọn..
C4.5: Một cải tiến của ID3, khắc phục một số hạn chế của ID3, bao gồm việc ưu tiên chọn các
thuộc tính có nhiều giá trị. (ID3 có xu hướng ưu tiên chọn các thuộc tính có nhiều giá trị hơn, vì
chúng thường có thể tạo ra nhiều tập con nhỏ hơn, dẫn đến giảm entropy nhiều hơn. Điều này
có thể dẫn đến việc tạo ra các cây quyết định quá sâu và phức tạp)
● Gain Ratio là tỷ lệ giữa Information Gain và Split Information (thông tin phân
tách). Split Information đo lường mức độ mà một thuộc tính chia tập dữ liệu
thành các nhóm khác nhau.
● Split Information sẽ tăng lên khi một thuộc tính có nhiều giá trị, vì thuộc tính đó
sẽ chia tập dữ liệu thành nhiều nhóm nhỏ hơn. Điều này làm giảm Gain Ratio,
nghĩa là thuộc tính có nhiều giá trị sẽ bị phạt nếu việc chia nhỏ không thực sự
hữu ích.
● #Example:
Consider an attribute like "day of the month". If we split on this attribute in ID3, we may end up
with 31 small subsets, each containing very few examples, and each subset may have nearly
pure classes, leading to high information gain.
However, in C4.5, the Split Information would be very high for this attribute because it's
splitting the data into many small subsets. As a result, the Gain Ratio would be lower,
preventing the algorithm from choosing it unless it truly provides useful information.
#Summary:
● ID3: Chooses attributes based on information gain, which can lead to overfitting when
attributes have many unique values.
● C4.5: Uses Gain Ratio, which adjusts for the number of values an attribute has by
penalizing attributes that split the data into many small, overly specific subsets,
reducing the risk of overfitting.
When building a decision tree, the splitting process continues until one of the following
stopping conditions is met:
● All attributes have been used: If all possible attributes have been considered along the
current branch, the splitting process stops. This means there are no more attributes
available to further divide the data at that node.
● Zero entropy: If all data instances at a leaf node belong to the same class (i.e., the
node's entropy is zero), the splitting process stops. This indicates that the data at that
node is pure and does not require further partitioning.
● Quá nhiều nhánh: Một cây quyết định quá phức tạp có thể có quá nhiều nhánh, dẫn đến
việc nó học được các mẫu nhiễu hoặc ngoại lệ trong dữ liệu huấn luyện.
● Phản ánh nhiễu: Một số nhánh có thể phản ánh các mẫu nhiễu hoặc ngoại lệ, làm cho
cây trở nên quá đặc biệt cho dữ liệu huấn luyện và kém hiệu quả với dữ liệu mới.
● Bagging (Bootstrap Aggregating): Là một kỹ thuật kết hợp nhiều mô hình học máy để
cải thiện độ chính xác. Nó tạo ra nhiều tập dữ liệu con bằng cách lấy mẫu có hoàn lại từ
tập dữ liệu gốc, sau đó huấn luyện một mô hình trên mỗi tập con và kết hợp kết quả của
các mô hình này.
● Random Forest: Tương tự như Bagging, Random Forest cũng sử dụng nhiều cây quyết
định. Tuy nhiên, khác với Bagging, Random Forest còn chọn ngẫu nhiên một tập con các
thuộc tính để xây dựng mỗi cây.
1. Bagging:
○ Với một tập dữ liệu huấn luyện S=(x1,y1),(x2,y2),…,(xn,yn), chọn ngẫu nhiên có
thay thế (sample with replacement) các ví dụ (xi,yi)(x_i, y_i)(xi,yi) từ tập dữ liệu
gốc để tạo ra các tập dữ liệu con. Mỗi tập con có cùng kích thước với tập dữ liệu
ban đầu.
○ Một cây quyết định (decision tree) được học từ mỗi tập con này.
○ Khi xây dựng mỗi cây quyết định, thay vì xem xét tất cả các thuộc tính (features)
ở mỗi nút (node), chỉ một tập hợp ngẫu nhiên các thuộc tính được chọn để đánh
giá. Điều này giúp giảm sự tương quan giữa các cây trong rừng và tăng tính đa
dạng (diversity) giữa các cây.
2. Xây dựng nhiều cây (K trees):
○ Lặp lại quá trình này K lần để tạo ra K cây quyết định. Mỗi cây sẽ hơi khác nhau
do sự ngẫu nhiên trong việc lấy mẫu và chọn thuộc tính.
3. Dự đoán:
○ Khi có một ví dụ mới, mỗi cây trong rừng sẽ đưa ra dự đoán riêng của nó.
○ Dự đoán cuối cùng được xác định bằng đa số phiếu (majority vote): dự đoán nào
được nhiều cây nhất đồng thuận sẽ là kết quả cuối cùng.
Random Forest: Similar to Bagging, Random Forest also uses multiple decision trees. However,
unlike Bagging, Random Forest randomly selects a subset of features to construct each tree.
Bagging:
Given a training set S = {(x1,y1), (x2,y2), ..., (xn,yn)}, randomly sample (with replacement)
examples (xi,yi) from the original dataset to create subsamples. Each subsample has the same
size as the original dataset.
Repeat this process K times to create K decision trees. Each tree will be slightly different due to
the randomness in sampling and feature selection.
Prediction:
When a new example is given, each tree in the forest makes its own prediction.
The final prediction is determined by a majority vote: the prediction that is agreed upon by the
most trees is the final result.
Diversity: Random Forest generally leads to more diverse trees due to the feature selection
process, which can improve the overall performance of the ensemble.
Bias-variance trade-off: Both Bagging and Random Forest can reduce variance, but Random
Forest can also help reduce bias by considering different subsets of features.
Về bản chất, ANN là một mô hình tính toán được thiết kế để mô phỏng cách hoạt động của não
người. Nó gồm một mạng lưới các nút (neuron) kết nối với nhau, mỗi nút xử lý thông tin và
truyền đạt kết quả đến các nút khác. Các kết nối giữa các nút có trọng số (weight) khác nhau,
đại diện cho mức độ ảnh hưởng của một nút lên nút khác.
Cấu trúc của Artificial Neural Network:
● Input Layer: Lớp đầu vào, nơi dữ liệu đầu vào được đưa vào mạng. Mỗi neuron trong lớp
này tương ứng với một đặc trưng (feature) của dữ liệu.
● Hidden Layers: Các lớp ẩn giữa lớp đầu vào và lớp đầu ra. Đây là nơi diễn ra các tính
toán chính của mạng. Một mạng có thể có nhiều lớp ẩn.
● Output Layer: Lớp đầu ra, nơi mạng cho ra kết quả cuối cùng. Số neuron ở lớp đầu ra
phụ thuộc vào loại bài toán (phân loại, hồi quy, v.v.).
● Neuron là đơn vị cơ bản của ANN, cũng giống như tế bào thần kinh trong não bộ. Mỗi
neuron nhận đầu vào, thực hiện tính toán và cho ra một đầu ra.
● Mỗi neuron có một hàm kích hoạt (activation function) để quyết định giá trị đầu ra của
nó dựa trên đầu vào. Một số hàm kích hoạt phổ biến là: sigmoid, tanh, và ReLU
(Rectified Linear Unit).
3, Trọng số (Weights): Mỗi kết nối giữa các neuron được gán một trọng số. Trọng số quyết định
mức độ ảnh hưởng của đầu vào đến đầu ra của neuron. Trong quá trình huấn luyện mạng, các
trọng số này được điều chỉnh để tối ưu hóa kết quả đầu ra. (Each connection between neurons
is assigned a weight. The weight determines how much the input affects the neuron's output.
During network training, these weights are adjusted to optimize the output.)
● Connection Strength:
○ Weights dictate how much influence the input signal from one neuron has on
the output of the next neuron.
○ A higher weight means the input signal has a stronger influence on the output,
while a lower weight means it has a weaker influence.
● Learning Process:
○ During the training of a neural network, weights are adjusted through a process
called backpropagation (truyền ngược).
○ The goal is to minimize the error between the network's predictions and the
actual target values.
○ By tweaking the weights, the network learns to make more accurate predictions.
● Transformation of Input:
○ When an input is fed into a neuron, it is multiplied by the corresponding weight.
This weighted input is then summed with other weighted inputs and passed
through an activation function to produce the output. This transformation
process allows the network to learn complex patterns in the data.
● Bias: Bên cạnh trọng số, mỗi neuron cũng có một giá trị bias. Bias giúp dịch chuyển giá
trị đầu ra của hàm kích hoạt để tăng tính linh hoạt trong việc học. (In addition to the
weights, each neuron also has a bias value. Bias helps shift the output value of the
activation function to increase flexibility in learning.)
○ A bias can be thought of as a weight with a constant input of 1. It allows the
activation function to be shifted to the left or right, providing additional flexibility
in the model.
#Common Activation Functions: In Artificial Neural Networks (ANN), activation functions play
a crucial role in determining whether a neuron should be activated or not by converting the
input signal into an output. Different types of activation functions have different
characteristics, and they are chosen based on the problem being solved.
● Sigmoid (Logistic) Function: The Sigmoid function outputs values in the range of (0,
1), making it useful for binary classification problems where the output needs to be
interpreted as probabilities.
○ Range: (0, 1)
○ Use cases: Typically used in the output layer for binary classification (phân loại
nhị phân).
○ Pros: Smooth gradient, output is probabilistic and can be interpreted as
probabilities.
○ Cons: Can suffer from vanishing gradient problem in deep networks, slow
convergence due to gradient saturation (when inputs are far from 0, gradient
becomes very small).
● Tanh (Hyperbolic Tangent) Function
○ The Tanh function is similar to the Sigmoid function but its output ranges from
(-1, 1). It is symmetric around the origin (đối xứng quanh gốc tọa độ), meaning
negative inputs produce negative outputs, and positive inputs produce positive
outputs.
○ Range: (-1, 1)
○ Use cases: Commonly used in hidden layers of neural networks.
○ Pros: Zero-centered output (helps with optimization), steeper gradient compared
to Sigmoid.
○ Cons: Still suffers from the vanishing gradient problem for very large or very
small inputs.
● The ReLU function: is one of the most popular activation functions in deep learning. It
outputs the input directly if it’s positive; otherwise, it outputs zero.
○ Range: [0, ∞)
○ Use cases: Most commonly used in hidden layers of deep networks.
○ Pros: Computationally efficient, does not saturate for positive inputs, helps
alleviate the vanishing gradient problem.
○ Cons: Dying ReLU problem: neurons can get "stuck" during training (i.e., output
zero for all inputs and stop learning) if the input is negative, causing the gradient
to become zero.
#Types of connectivity:
Learn patterns and relationships within a given dataset by adjusting the weights during the
learning process
● Purposes
○ Pattern Recognition: Identifying patterns in data, such as recognizing images,
detecting anomalies, or understanding speech.
○ Prediction: Making predictions based on historical data, such as forecasting stock
prices or weather conditions.
○ Classification: Categorizing data into predefined classes, such as spam
detection in emails or diagnosis in medical imaging.
○ Function Approximation: Approximating complex functions that are difficult to
model mathematically.
● Initialize weights and biases, typically with small random values to break symmetry
(phá vỡ tính đối xứng).
● Initialization methods (phương pháp khởi tạo) like Xavier or He initialization can be used
depending on the activation functions.
● Pass the input data through the network, layer by layer, applying weights, biases, and
activation functions to compute the output.
● Calculate the predicted output for the given input.
● Define a loss function (e.g., Mean Squared Error for regression, Cross-Entropy Loss for
classification).
● Compute the loss by comparing the predicted output with the actual target values.
○ Sau khi mạng đưa ra kết quả đầu ra, một hàm mất mát (loss function) sẽ tính
toán mức độ sai lệch giữa đầu ra dự đoán và kết quả thực tế. Hàm mất mát
thường được sử dụng để đo lường hiệu suất của mô hình.
4. Backward Propagation
● Calculate the gradient of the loss function with respect to each weight and bias in the
network. (Tính toán độ dốc của hàm mất mát theo từng trọng số và độ lệch trong mạng)
● Use these gradients to update the weights and biases in the direction that minimizes
the loss function.
● This step involves the chain rule of calculus to propagate the error backward through
the network.
● Use an optimization algorithm (e.g., Stochastic Gradient Descent, Adam) to update the
weights and biases based on the gradients computed during backpropagation.
1. Perceptron (P):
● The Perceptron is the simplest type of artificial neural network and serves as the
building block for more complex networks. It models a single neuron and is used to
model logic gates for performing the logical operation.
How it works:
● Straight forward: Information flows in a single direction, from the input layer to the
output layer.
● Modeling logic gates: Perceptron can be used to model logic gates such as AND, OR,
and NOT.
Training:
● Supervised Learning: Perceptrons are trained using supervised learning, where the
network is provided with input data and the corresponding correct output.
● Backpropagation: While the backpropagation algorithm is more commonly associated
with multilayer neural networks, it can be applied to perceptrons to update the weights
and biases.
○ Thuật toán back-propagation được sử dụng để cập nhật các trọng số của
perceptron dựa trên lỗi giữa đầu ra dự đoán và đầu ra mong muốn. Lỗi này
thường được tính bằng các phương pháp như sai số bình phương trung bình
(MSE).
● Application: The simple structure limits the applications, but they are popularly
combined with other networks to form new NN structures.
2. Feedforward Neural Network (FFNN)
A Feedforward Neural Network (FFNN) is a more advanced type of artificial neural network
than the perceptron. It consists of multiple layers of neurons, making it capable of solving more
complex problems.
● Single Direction: The connection is all straight forward from the input to the output.
There is no loop going back to the previous layers. The only time using the
backpropregration is in the training phase to minimise the differences between the
target value and the ANN output.
○ The error (difference between predicted and actual output) is propagated back
through the network, and the weights are updated to reduce the error.
○ The process repeats for multiple iterations (epochs) until the network's
predictions are accurate.
● When deploying the trained ANN in an application, the computation is very fast and
thus is capable of using in real-time scenario.
● Input Layer: This is where the input data is fed into the network. Each node in this layer
represents a feature of the data.
● Hidden Layers: Located between the input and output layers, hidden layers perform
complex calculations to extract high-level features from the data. The number of
hidden layers and the number of nodes in each hidden layer can vary depending on the
network architecture and the specific problem.
● Output Layer: This layer provides the final output of the neural network. The number of
nodes in the output layer corresponds tolecture 3 neural networks 7 the number of
classes we want to predict
Q1:Để biết một data set được classify (phân loại) tốt hay không, bạn cần sử dụng một số chỉ
số và kỹ thuật đánh giá hiệu suất của mô hình. Dưới đây là các bước và các chỉ số phổ biến
được sử dụng để đánh giá hiệu quả của mô hình phân loại:
Classification Methods:
Classification methods are used when the output variable is a discrete category or class.
These methods focus on predicting which class a data point belongs to.
Regression Methods:
Regression methods are used when the output variable is continuous and not categorical.
These methods aim to predict a number.
● Use classification when you need to categorize data points into distinct groups (e.g.,
"yes" or "no").
● Use regression when you're predicting a continuous quantity (e.g., predicting house
prices).
Để biết một data set được classify (phân loại) tốt hay không, bạn cần sử dụng một số chỉ số và
kỹ thuật đánh giá hiệu suất của mô hình. Dưới đây là các bước và các chỉ số phổ biến được sử
dụng để đánh giá hiệu quả của mô hình phân loại:
● Accuracy đo lường tỷ lệ phần trăm các dự đoán chính xác của mô hình trên tổng số
mẫu.
● Công thức: Accuracy=Soˆˊ dự đoaˊn đuˊngTổng soˆˊ maˆ˜u\text{Accuracy} =
\frac{\text{Số dự đoán đúng}}{\text{Tổng số mẫu}}Accuracy=Tổng soˆˊ maˆ˜uSoˆˊ dự
đoaˊn đuˊng
● Tuy nhiên, accuracy không phải lúc nào cũng phản ánh chính xác chất lượng của mô
hình, đặc biệt khi dữ liệu bị mất cân bằng (ví dụ: 90% lớp A và 10% lớp B). Trong trường
hợp đó, các chỉ số khác sẽ quan trọng hơn.
2. Ma trận nhầm lẫn (Confusion Matrix)
Ma trận nhầm lẫn cho phép bạn hiểu rõ hơn cách mô hình phân loại từng lớp cụ thể.
6. Cross-Validation
Here's why:
● Small K values: When the value of K is too small, the model becomes overly sensitive
to the local structure of the data. This can lead to it memorizing the training data rather
than learning general patterns, causing overfitting.
● High-dimensional data: In high-dimensional spaces, the "curse of dimensionality" can
come into play. This phenomenon makes it difficult for KNN to find meaningful
neighbors, leading to overfitting.
● Noisy data: If the data contains a lot of noise or outliers, KNN can be easily influenced
by these points, leading to overfitting.
● Choose an appropriate K value: Experiment with different K values to find the optimal
balance between underfitting and overfitting. Cross-validation can help you select the
best K.
● Consider dimensionality reduction techniques: Techniques like PCA or t-SNE can help
reduce the dimensionality of your data, making it easier for KNN to find meaningful
neighbors.
● Handle outliers: Identify and remove or handle outliers in your data to prevent them
from unduly influencing the model.
● Use distance metrics that are appropriate for your data: The choice of distance metric
can significantly impact the performance of KNN. Consider using metrics like Manhattan
distance or cosine similarity for different types of data.
#Data types and structure
Types of data:
Quantitative:
● Discrete (distinct/separate value): It can only have specific values. Data can be
“countedˮ. Discrete data includes discrete variables that are finite, numeric, countable,
and non-negative integers.Eg: dice
● Continuous (any value in an interval): It can take on value in an interval(1 khoảng).
Variables in continuous data sets often carry decimal points, with the number stretching
out as far as possible. Data that can be “measuredˮ. Eg: Temperature Qualitativelecture
2 key issues of machine learning 4 Nominal: Nominal data is categorical and represents
labels or names without any inherent order.
Qualitative:
● Nominal: Nominal data is categorical and represents labels or names without any
inherent order.
○ This type of data categorizes items based on their characteristics, but the
categories don't have a ranked or logical sequence
○ You can think of it as simple "labels" that differentiate one category from
another
○ For example Gender: Male, Female, Non-binary Blood Type: A, B, AB, O Ordinal:
Ordinal data is also categorical, but unlike nominal data, it has a meaningful
order or ranking.
● Ordinal:Ordinal data is also categorical, but unlike nominal data, it has a meaningful
order or ranking.
○ However, the intervals between these ranked categories are not necessarily
equal or known.
○ Ordinal data provides a sense of sequence, but it doesn't analyze the difference
between each rank.
○ VD: Educational level: High school, Bachelorʼs Degree, Masterʼs Degree, PhD
■ Movie Ratings: 1 star, 2 stars, 3 stars, 4 stars, 5 stars
Conversion
● Definition: Overfitting occurs when a machine learning model learns the training data
too well, including noise and details that don't generalize to new, unseen data.
● Phenomenon: The model performs exceptionally well on the training data but poorly
on the test data. This happens when the model is overly complex relative to the amount
of data or the noise in the data.
Example: A Decision Tree that perfectly classifies the training data but fails to generalize to
unseen examples because it has learned irrelevant patterns.
General Solutions:
Algorithm-Specific Solutions:
Q2- What is the difference between supervised and unsupervised machine learning? More
reading: What is the difference between supervised and unsupervised machine learning?
(Quora) Supervised learning requires training labeled data. For example, in order to do
classification (a supervised learning task), you’ll need to first label the data you’ll use to train
the model to classify data into your labeled groups. Unsupervised learning, in contrast, does
not require labeling data explicitly.
Q7- Why is “Naive” Bayes naive? More reading: Why is “naive Bayes” naive? (Quora) Despite
its practical applications, especially in text mining, Naive Bayes is considered “Naive” because it
makes an assumption that is virtually impossible to see in real-life data: the conditional
probability is calculated as the pure product of the individual probabilities of components. This
implies the absolute independence of features — a condition probably never met in real life. As
a Quora commenter put it whimsically, a Naive Bayes classifier that figured out that you liked
pickles and ice cream would probably naively recommend you a pickle ice cream.
Q13- What is deep learning, and how does it contrast with other machine learning
algorithms? More reading: Deep learning (Wikipedia) Deep learning is a subset of machine
learning that is concerned with neural networks: how to use backpropagation and certain
principles from neuroscience to more accurately model large sets of unlabelled or
semi-structured data. In that sense, deep learning represents an unsupervised learning
algorithm that learns representations of data through the use of neural nets.
Q15- What cross-validation technique would you use on a time series dataset? More
reading: Using k-fold cross-validation for time-series model selection (CrossValidated) Instead
of using standard k-folds cross-validation, you have to pay attention to the fact that a time
series is not randomly distributed data — it is inherently ordered by chronological order. If a
pattern emerges in later time periods for example, your model may still pick up on it even if
that effect doesn’t hold in earlier years! You’ll want to do something like forward chaining
where you’ll be able to model on past data then look at forward-facing data.
Q16- How is a decision tree pruned? More reading: Pruning (decision trees) Pruning is what
happens in decision trees when branches that have weak predictive power are removed in
order to reduce the complexity of the model and increase the predictive accuracy of a decision
tree model. Pruning can happen bottom-up and top-down, with approaches such as reduced
error pruning and cost complexity pruning. Reduced error pruning is perhaps the simplest
version: replace each node. If it doesn’t decrease predictive accuracy, keep it pruned.
Q20- When should you use classification over regression? More reading: Regression vs
Classification (Math StackExchange) Classification produces discrete values and dataset to
strict categories, while regression gives you continuous results that allow you to better
distinguish differences between individual points. You would use classification over regression
if you wanted your results to reflect the belongingness of data points in your dataset to certain
explicit categories (ex: If you wanted to know whether a name was male or female rather than
just how correlated they were with male and female names.)
Q22- How do you ensure you’re not overfitting with a model? More reading: How can I avoid
overfitting? (Quora) This is a simple restatement of a fundamental problem in machine
learning: the possibility of overfitting training data and carrying the noise of that data through
to the test set, thereby providing inaccurate generalizations. There are three main methods to
avoid overfitting: 1- Keep the model simpler: reduce variance by taking into account fewer
variables and parameters, thereby removing some of the noise in the training data. 2- Use
cross-validation techniques such as k-folds cross-validation. 3- Use regularization techniques
such as LASSO that penalize certain model parameters if they’re likely to cause overfitting.
Q23- What evaluation approaches would you work to gauge the effectiveness of a machine
learning model? More reading: How to Evaluate Machine Learning Algorithms (Machine
Learning Mastery) You would first split the dataset into training and test sets, or perhaps use
cross-validation techniques to further segment the dataset into composite sets of training and
test sets within the data. You should then implement a choice selection of performance metrics:
here is a fairly comprehensive list. You could use measures such as the F1 score, the accuracy,
and the confusion matrix. What’s important here is to demonstrate that you understand the
nuances of how a model is measured and how to choose the right performance measures for
the right situations.