主頁 >  其他 > 【OpenCV4 官方檔案】機器學習概述

【OpenCV4 官方檔案】機器學習概述

2021-09-07 09:58:39 其他

Machine Learning Overview

文章目錄

  • Machine Learning Overview
  • 1、Training Data (訓練資料)
  • 2、Normal Bayes Classifier (正態貝葉斯分類器)
  • 3、K-Nearest Neighbors(K-鄰近)
  • 4、Support Vector Machines (支持向量機)
  • 5、Decision Trees (決策樹)
  • 6、Boosting(提升方法)
  • 7、Random Trees(隨機樹)
  • 8、Expectation Maximization (期望最大化)
  • 9、Neural Networks (神經網路)
  • 10、Logistic Regression (邏輯回歸)

1、Training Data (訓練資料)

在機器學習演算法中,訓練資料包括幾個組成部分:

  • A set of training samples. Each training sample is a vector of values (in Computer Vision it’s
    sometimes referred to as feature vector). Usually all the vectors have the same number of
    components (features); OpenCV ml module assumes that. Each feature can be ordered (i.e. its
    values are floating-point numbers that can be compared with each other and strictly ordered,
    i.e. sorted) or categorical (i.e. its value belongs to a fixed set of values that can be
    integers, strings etc.).
  • Optional set of responses corresponding to the samples. Training data with no responses is used
    in unsupervised learning algorithms that learn structure of the supplied data based on distances
    between different samples. Training data with responses is used in supervised learning
    algorithms, which learn the function mapping samples to responses. Usually the responses are
    scalar values, ordered (when we deal with regression problem) or categorical (when we deal with
    classification problem; in this case the responses are often called “labels”). Some algorithms,
    most noticeably Neural networks, can handle not only scalar, but also multi-dimensional or
    vector responses.
  • Another optional component is the mask of missing measurements. Most algorithms require all the
    components in all the training samples be valid, but some other algorithms, such as decision
    trees, can handle the cases of missing measurements.
  • In the case of classification problem user may want to give different weights to different
    classes. This is useful, for example, when:
    • user wants to shift prediction accuracy towards lower false-alarm rate or higher hit-rate.
    • user wants to compensate for significantly different amounts of training samples from
      different classes.
  • In addition to that, each training sample may be given a weight, if user wants the algorithm to
    pay special attention to certain training samples and adjust the training model accordingly.
  • Also, user may wish not to use the whole training data at once, but rather use parts of it, e.g.
    to do parameter optimization via cross-validation procedure.

As you can see, training data can have rather complex structure; besides, it may be very big and/or
not entirely available, so there is need to make abstraction for this concept. In OpenCV ml there is
cv::ml::TrainData class for that.

@sa cv::ml::TrainData

2、Normal Bayes Classifier (正態貝葉斯分類器)

這個簡單的分類模型假設每個類別的特征向量都是正態分布(盡管不一定是獨立分布),因此,整個資料分布函式被假定為高斯混合物,每類有一個成分,使用訓練資料演算法估計每個類別的平均向量和協方差矩陣,然后用它們進行預測,

@sa cv::ml::NormalBayesClassifier

3、K-Nearest Neighbors(K-鄰近)

The algorithm caches all training samples and predicts the response for a new sample by analyzing a
certain number (K) of the nearest neighbors of the sample using voting, calculating weighted
sum, and so on. The method is sometimes referred to as “learning by example” because for prediction
it looks for the feature vector with a known response that is closest to the given vector.

@sa cv::ml::KNearest

4、Support Vector Machines (支持向量機)

Originally, support vector machines (SVM) was a technique for building an optimal binary (2-class)
classifier. Later the technique was extended to regression and clustering problems. SVM is a partial
case of kernel-based methods. It maps feature vectors into a higher-dimensional space using a kernel
function and builds an optimal linear discriminating function in this space or an optimal hyper-
plane that fits into the training data. In case of SVM, the kernel is not defined explicitly.
Instead, a distance between any 2 points in the hyper-space needs to be defined.

The solution is optimal, which means that the margin between the separating hyper-plane and the
nearest feature vectors from both classes (in case of 2-class classifier) is maximal. The feature
vectors that are the closest to the hyper-plane are called support vectors, which means that the
position of other vectors does not affect the hyper-plane (the decision function).

SVM implementation in OpenCV is based on @cite LibSVM

@sa cv::ml::SVM

Prediction with SVM

StatModel::predict(samples, results, flags) should be used. Pass flags=StatModel::RAW_OUTPUT to get
the raw response from SVM (in the case of regression, 1-class or 2-class classification problem).

5、Decision Trees (決策樹)

The ML classes discussed in this section implement Classification and Regression Tree algorithms
described in @cite Breiman84 .

The class cv::ml::DTrees represents a single decision tree or a collection of decision trees. It’s
also a base class for RTrees and Boost.

A decision tree is a binary tree (tree where each non-leaf node has two child nodes). It can be used
either for classification or for regression. For classification, each tree leaf is marked with a
class label; multiple leaves may have the same label. For regression, a constant is also assigned to
each tree leaf, so the approximation function is piecewise constant.

@sa cv::ml::DTrees

(1) Predicting with Decision Trees

To reach a leaf node and to obtain a response for the input feature vector, the prediction procedure
starts with the root node. From each non-leaf node the procedure goes to the left (selects the left
child node as the next observed node) or to the right based on the value of a certain variable whose
index is stored in the observed node. The following variables are possible:

  • Ordered variables. The variable value is compared with a threshold that is also stored in
    the node. If the value is less than the threshold, the procedure goes to the left. Otherwise, it
    goes to the right. For example, if the weight is less than 1 kilogram, the procedure goes to the
    left, else to the right.

  • Categorical variables. A discrete variable value is tested to see whether it belongs to a
    certain subset of values (also stored in the node) from a limited set of values the variable
    could take. If it does, the procedure goes to the left. Otherwise, it goes to the right. For
    example, if the color is green or red, go to the left, else to the right.

So, in each node, a pair of entities (variable_index , decision_rule (threshold/subset) ) is used.
This pair is called a split (split on the variable variable_index ). Once a leaf node is reached,
the value assigned to this node is used as the output of the prediction procedure.

Sometimes, certain features of the input vector are missed (for example, in the darkness it is
difficult to determine the object color), and the prediction procedure may get stuck in the certain
node (in the mentioned example, if the node is split by color). To avoid such situations, decision
trees use so-called surrogate splits. That is, in addition to the best “primary” split, every tree
node may also be split to one or more other variables with nearly the same results.

(2) Training Decision Trees

The tree is built recursively, starting from the root node. All training data (feature vectors and
responses) is used to split the root node. In each node the optimum decision rule (the best
“primary” split) is found based on some criteria. In machine learning, gini “purity” criteria are
used for classification, and sum of squared errors is used for regression. Then, if necessary, the
surrogate splits are found. They resemble the results of the primary split on the training data. All
the data is divided using the primary and the surrogate splits (like it is done in the prediction
procedure) between the left and the right child node. Then, the procedure recursively splits both
left and right nodes. At each node the recursive procedure may stop (that is, stop splitting the
node further) in one of the following cases:

  • Depth of the constructed tree branch has reached the specified maximum value.
  • Number of training samples in the node is less than the specified threshold when it is not
    statistically representative to split the node further.
  • All the samples in the node belong to the same class or, in case of regression, the variation is
    too small.
  • The best found split does not give any noticeable improvement compared to a random choice.

When the tree is built, it may be pruned using a cross-validation procedure, if necessary. That is,
some branches of the tree that may lead to the model overfitting are cut off. Normally, this
procedure is only applied to standalone decision trees. Usually tree ensembles build trees that are
small enough and use their own protection schemes against overfitting.

(3) Variable Importance

Besides the prediction that is an obvious use of decision trees, the tree can be also used for
various data analyses. One of the key properties of the constructed decision tree algorithms is an
ability to compute the importance (relative decisive power) of each variable. For example, in a spam
filter that uses a set of words occurred in the message as a feature vector, the variable importance
rating can be used to determine the most “spam-indicating” words and thus help keep the dictionary
size reasonable.

Importance of each variable is computed over all the splits on this variable in the tree, primary
and surrogate ones. Thus, to compute variable importance correctly, the surrogate splits must be
enabled in the training parameters, even if there is no missing data.

6、Boosting(提升方法)

A common machine learning task is supervised learning. In supervised learning, the goal is to learn
the functional relationship \fKaTeX parse error: Undefined control sequence: \f at position 12: F: y = F(x)\?f? between the input \fKaTeX parse error: Undefined control sequence: \f at position 2: x\?f? and the output \fKaTeX parse error: Undefined control sequence: \f at position 2: y\?f? .
Predicting the qualitative output is called classification, while predicting the quantitative
output is called regression.

Boosting is a powerful learning concept that provides a solution to the supervised classification
learning task. It combines the performance of many “weak” classifiers to produce a powerful
committee @cite HTF01 . A weak classifier is only required to be better than chance, and thus can be
very simple and computationally inexpensive. However, many of them smartly combine results to a
strong classifier that often outperforms most “monolithic” strong classifiers such as SVMs and
Neural Networks.

Decision trees are the most popular weak classifiers used in boosting schemes. Often the simplest
decision trees with only a single split node per tree (called stumps ) are sufficient.

The boosted model is based on \fKaTeX parse error: Undefined control sequence: \f at position 2: N\?f? training examples \fKaTeX parse error: Undefined control sequence: \f at position 14: {(x_i,y_i)}1N\?f? with \fKaTeX parse error: Undefined control sequence: \f at position 13: x_i \in{R^K}\?f?
and \fKaTeX parse error: Undefined control sequence: \f at position 16: y_i \in{-1, +1}\?f? . \fKaTeX parse error: Undefined control sequence: \f at position 4: x_i\?f? is a \fKaTeX parse error: Undefined control sequence: \f at position 2: K\?f? -component vector. Each component encodes a
feature relevant to the learning task at hand. The desired two-class output is encoded as -1 and +1.

Different variants of boosting are known as Discrete Adaboost, Real AdaBoost, LogitBoost, and Gentle
AdaBoost @cite FHT98 . All of them are very similar in their overall structure. Therefore, this
chapter focuses only on the standard two-class Discrete AdaBoost algorithm, outlined below.
Initially the same weight is assigned to each sample (step 2). Then, a weak classifier
\fKaTeX parse error: Undefined control sequence: \f at position 9: f_{m(x)}\?f? is trained on the weighted training data (step 3a). Its weighted training error and
scaling factor \fKaTeX parse error: Undefined control sequence: \f at position 4: c_m\?f? is computed (step 3b). The weights are increased for training samples that
have been misclassified (step 3c). All weights are then normalized, and the process of finding the
next weak classifier continues for another \fKaTeX parse error: Undefined control sequence: \f at position 2: M\?f? -1 times. The final classifier \fKaTeX parse error: Undefined control sequence: \f at position 5: F(x)\?f? is the
sign of the weighted sum over the individual weak classifiers (step 4).

Two-class Discrete AdaBoost Algorithm

  • Set \fKaTeX parse error: Undefined control sequence: \f at position 2: N\?f? examples \fKaTeX parse error: Undefined control sequence: \f at position 14: {(x_i,y_i)}1N\?f? with \fKaTeX parse error: Undefined control sequence: \f at position 30: …y_i \in{-1, +1}\?f? .

  • Assign weights as \fKaTeX parse error: Undefined control sequence: \f at position 23: …/N, i = 1,...,N\?f? .

  • Repeat for \fKaTeX parse error: Undefined control sequence: \f at position 14: m = 1,2,...,M\?f? :

    • Fit the classifier \fKaTeX parse error: Undefined control sequence: \f at position 17: …_m(x) \in{-1,1}\?f?, using weights \fKaTeX parse error: Undefined control sequence: \f at position 4: w_i\?f? on the training data.

    • Compute \fKaTeX parse error: Undefined control sequence: \f at position 64: …- err_m)/err_m)\?f? .

    • Set \fKaTeX parse error: Undefined control sequence: \f at position 68: … i = 1,2,...,N,\?f? and
      renormalize so that \fKaTeX parse error: Undefined control sequence: \f at position 17: …Sigma i w_i = 1\?f? .

  • Classify new samples x using the formula: \fKaTeX parse error: Undefined control sequence: \f at position 41: … 1M c_m f_m(x))\?f? .

@note Similar to the classical boosting methods, the current implementation supports two-class
classifiers only. For M > 2 classes, there is the AdaBoost.MH algorithm (described in
@cite FHT98) that reduces the problem to the two-class problem, yet with a much larger training set.

To reduce computation time for boosted models without substantially losing accuracy, the influence
trimming technique can be employed. As the training algorithm proceeds and the number of trees in
the ensemble is increased, a larger number of the training samples are classified correctly and with
increasing confidence, thereby those samples receive smaller weights on the subsequent iterations.
Examples with a very low relative weight have a small impact on the weak classifier training. Thus,
such examples may be excluded during the weak classifier training without having much effect on the
induced classifier. This process is controlled with the weight_trim_rate parameter. Only examples
with the summary fraction weight_trim_rate of the total weight mass are used in the weak classifier
training. Note that the weights for all training examples are recomputed at each training
iteration. Examples deleted at a particular iteration may be used again for learning some of the
weak classifiers further @cite FHT98

@sa cv::ml::Boost

Prediction with Boost

StatModel::predict(samples, results, flags) should be used. Pass flags=StatModel::RAW_OUTPUT to get
the raw sum from Boost classifier.

7、Random Trees(隨機樹)

Random trees have been introduced by Leo Breiman and Adele Cutler:
http://www.stat.berkeley.edu/users/breiman/RandomForests/ . The algorithm can deal with both
classification and regression problems. Random trees is a collection (ensemble) of tree predictors
that is called forest further in this section (the term has been also introduced by L. Breiman).
The classification works as follows: the random trees classifier takes the input feature vector,
classifies it with every tree in the forest, and outputs the class label that received the majority
of “votes”. In case of a regression, the classifier response is the average of the responses over
all the trees in the forest.

All the trees are trained with the same parameters but on different training sets. These sets are
generated from the original training set using the bootstrap procedure: for each training set, you
randomly select the same number of vectors as in the original set ( =N ). The vectors are chosen
with replacement. That is, some vectors will occur more than once and some will be absent. At each
node of each trained tree, not all the variables are used to find the best split, but a random
subset of them. With each node a new subset is generated. However, its size is fixed for all the
nodes and all the trees. It is a training parameter set to \fKaTeX parse error: Undefined control sequence: \f at position 29: …_of\_variables}\?f? by
default. None of the built trees are pruned.

In random trees there is no need for any accuracy estimation procedures, such as cross-validation or
bootstrap, or a separate test set to get an estimate of the training error. The error is estimated
internally during the training. When the training set for the current tree is drawn by sampling with
replacement, some vectors are left out (so-called oob (out-of-bag) data ). The size of oob data is
about N/3 . The classification error is estimated by using this oob-data as follows:

  • Get a prediction for each vector, which is oob relative to the i-th tree, using the very i-th
    tree.

  • After all the trees have been trained, for each vector that has ever been oob, find the
    class-winner for it (the class that has got the majority of votes in the trees where
    the vector was oob) and compare it to the ground-truth response.

  • Compute the classification error estimate as a ratio of the number of misclassified oob vectors
    to all the vectors in the original data. In case of regression, the oob-error is computed as the
    squared error for oob vectors difference divided by the total number of vectors.

For the random trees usage example, please, see letter_recog.cpp sample in OpenCV distribution.

@sa cv::ml::RTrees

References:

  • Machine Learning, Wald I, July 2002.
    http://stat-www.berkeley.edu/users/breiman/wald2002-1.pdf
  • Looking Inside the Black Box, Wald II, July 2002.
    http://stat-www.berkeley.edu/users/breiman/wald2002-2.pdf
  • Software for the Masses, Wald III, July 2002.
    http://stat-www.berkeley.edu/users/breiman/wald2002-3.pdf
  • And other articles from the web site
    http://www.stat.berkeley.edu/users/breiman/RandomForests/cc_home.htm

8、Expectation Maximization (期望最大化)

The Expectation Maximization(EM) algorithm estimates the parameters of the multivariate probability
density function in the form of a Gaussian mixture distribution with a specified number of mixtures.

Consider the set of the N feature vectors { \fKaTeX parse error: Undefined control sequence: \f at position 19: …, x_2,...,x_{N}\?f? } from a d-dimensional Euclidean
space drawn from a Gaussian mixture:

\f[p(x;a_k,S_k, \pi _k) = \sum _{k=1}^{m} \pi _kp_k(x), \quad \pi _k \geq 0, \quad \sum _{k=1}^{m} \pi _k=1,\f]

\f[p_k(x)= \varphi (x;a_k,S_k)= \frac{1}{(2\pi){d/2}\mid{S_k}\mid{1/2}} exp \left { - \frac{1}{2} (x-a_k)TS_k{-1}(x-a_k) \right } ,\f]

where \fKaTeX parse error: Undefined control sequence: \f at position 2: m\?f? is the number of mixtures, \fKaTeX parse error: Undefined control sequence: \f at position 4: p_k\?f? is the normal distribution density with the mean
\fKaTeX parse error: Undefined control sequence: \f at position 4: a_k\?f? and covariance matrix \fKaTeX parse error: Undefined control sequence: \f at position 4: S_k\?f?, \fKaTeX parse error: Undefined control sequence: \f at position 6: \pi_k\?f? is the weight of the k-th mixture. Given the
number of mixtures \fKaTeX parse error: Undefined control sequence: \f at position 2: M\?f? and the samples \fKaTeX parse error: Undefined control sequence: \f at position 4: x_i\?f?, \fKaTeX parse error: Undefined control sequence: \f at position 7: i=1..N\?f? the algorithm finds the maximum-
likelihood estimates (MLE) of all the mixture parameters, that is, \fKaTeX parse error: Undefined control sequence: \f at position 4: a_k\?f?, \fKaTeX parse error: Undefined control sequence: \f at position 4: S_k\?f? and
\fKaTeX parse error: Undefined control sequence: \f at position 6: \pi_k\?f? :

\f[L(x, \theta )=logp(x, \theta )= \sum _{i=1}^{N}log \left ( \sum _{k=1}^{m} \pi _kp_k(x) \right ) \to \max _{ \theta \in \Theta },\f]

\f[\Theta = \left { (a_k,S_k, \pi _k): a_k \in \mathbbm{R} d,S_k=S_kT>0,S_k \in \mathbbm{R} ^{d \times d}, \pi _k \geq 0, \sum _{k=1}^{m} \pi _k=1 \right } .\f]

The EM algorithm is an iterative procedure. Each iteration includes two steps. At the first step
(Expectation step or E-step), you find a probability \fKaTeX parse error: Undefined control sequence: \f at position 8: p_{i,k}\?f? (denoted \fKaTeX parse error: Undefined control sequence: \f at position 13: \alpha_{i,k}\?f? in
the formula below) of sample i to belong to mixture k using the currently available mixture
parameter estimates:

\f[\alpha {ki} = \frac{\pi_k\varphi(x;a_k,S_k)}{\sum\limits{j=1}^{m}\pi_j\varphi(x;a_j,S_j)} .\f]

At the second step (Maximization step or M-step), the mixture parameter estimates are refined using
the computed probabilities:

\f[\pi k= \frac{1}{N} \sum {i=1}^{N} \alpha {ki}, \quad a_k= \frac{\sum\limits{i=1}{N}\alpha_{ki}x_i}{\sum\limits_{i=1}{N}\alpha{ki}} , \quad S_k= \frac{\sum\limits{i=1}{N}\alpha_{ki}(x_i-a_k)(x_i-a_k)T}{\sum\limits_{i=1}^{N}\alpha_{ki}}\f]

Alternatively, the algorithm may start with the M-step when the initial values for \fKaTeX parse error: Undefined control sequence: \f at position 8: p_{i,k}\?f? can
be provided. Another alternative when \fKaTeX parse error: Undefined control sequence: \f at position 8: p_{i,k}\?f? are unknown is to use a simpler clustering
algorithm to pre-cluster the input samples and thus obtain initial \fKaTeX parse error: Undefined control sequence: \f at position 8: p_{i,k}\?f? . Often (including
machine learning) the k-means algorithm is used for that purpose.

One of the main problems of the EM algorithm is a large number of parameters to estimate. The
majority of the parameters reside in covariance matrices, which are \fKaTeX parse error: Undefined control sequence: \f at position 11: d \times d\?f? elements each
where \fKaTeX parse error: Undefined control sequence: \f at position 2: d\?f? is the feature space dimensionality. However, in many practical problems, the
covariance matrices are close to diagonal or even to \fKaTeX parse error: Undefined control sequence: \f at position 8: \mu_k*I\?f? , where \fKaTeX parse error: Undefined control sequence: \f at position 2: I\?f? is an identity
matrix and \fKaTeX parse error: Undefined control sequence: \f at position 6: \mu_k\?f? is a mixture-dependent “scale” parameter. So, a robust computation scheme
could start with harder constraints on the covariance matrices and then use the estimated parameters
as an input for a less constrained optimization problem (often a diagonal covariance matrix is
already a good enough approximation).

@sa cv::ml::EM

References:

  • Bilmes98 J. A. Bilmes. A Gentle Tutorial of the EM Algorithm and its Application to Parameter
    Estimation for Gaussian Mixture and Hidden Markov Models
    . Technical Report TR-97-021,
    International Computer Science Institute and Computer Science Division, University of California
    at Berkeley, April 1998.

9、Neural Networks (神經網路)

ML implements feed-forward artificial neural networks or, more particularly, multi-layer perceptrons
(MLP), the most commonly used type of neural networks. MLP consists of the input layer, output
layer, and one or more hidden layers. Each layer of MLP includes one or more neurons directionally
linked with the neurons from the previous and the next layer. The example below represents a 3-layer
perceptron with three inputs, two outputs, and the hidden layer including five neurons:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-0gqQLW7W-1630895554316)(pics/mlp.png)]

All the neurons in MLP are similar. Each of them has several input links (it takes the output values
from several neurons in the previous layer as input) and several output links (it passes the
response to several neurons in the next layer). The values retrieved from the previous layer are
summed up with certain weights, individual for each neuron, plus the bias term. The sum is
transformed using the activation function \fKaTeX parse error: Undefined control sequence: \f at position 2: f\?f? that may be also different for different neurons.

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-8F5LNpg7-1630895554319)(pics/neuron_model.png)]

In other words, given the outputs \fKaTeX parse error: Undefined control sequence: \f at position 4: x_j\?f? of the layer \fKaTeX parse error: Undefined control sequence: \f at position 2: n\?f? , the outputs \fKaTeX parse error: Undefined control sequence: \f at position 4: y_i\?f? of the
layer \fKaTeX parse error: Undefined control sequence: \f at position 4: n+1\?f? are computed as:

\f[u_i = \sum j (w^{n+1}{i,j}*x_j) + w^{n+1}_{i,bias}\f]

\f[y_i = f(u_i)\f]

Different activation functions may be used. ML implements three standard functions:

  • Identity function ( cv::ml::ANN_MLP::IDENTITY ): \fKaTeX parse error: Undefined control sequence: \f at position 7: f(x)=x\?f?

  • Symmetrical sigmoid ( cv::ml::ANN_MLP::SIGMOID_SYM ): \fKaTeX parse error: Undefined control sequence: \f at position 46: …1+e^{-\alpha x}\?f? ), which is the default choice for MLP. The standard sigmoid with
    \fKaTeX parse error: Undefined control sequence: \f at position 20: …a =1, \alpha =1\?f? is shown below:

    [外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-RchHy0Ri-1630895554320)(pics/sigmoid_bipolar.png)]

  • Gaussian function ( cv::ml::ANN_MLP::GAUSSIAN ): \fKaTeX parse error: Undefined control sequence: \f at position 27: …e^{-\alpha x*x}\?f? , which is not
    completely supported at the moment.

In ML, all the neurons have the same activation functions, with the same free parameters (
\fKaTeX parse error: Undefined control sequence: \f at position 14: \alpha, \beta\?f? ) that are specified by user and are not altered by the training algorithms.

So, the whole trained network works as follows:

  1. Take the feature vector as input. The vector size is equal to the size of the input layer.
  2. Pass values as input to the first hidden layer.
  3. Compute outputs of the hidden layer using the weights and the activation functions.
  4. Pass outputs further downstream until you compute the output layer.

So, to compute the network, you need to know all the weights \fKaTeX parse error: Undefined control sequence: \f at position 15: w^{n+1)}_{i,j}\?f? . The weights are
computed by the training algorithm. The algorithm takes a training set, multiple input vectors with
the corresponding output vectors, and iteratively adjusts the weights to enable the network to give
the desired response to the provided input vectors.

The larger the network size (the number of hidden layers and their sizes) is, the more the potential
network flexibility is. The error on the training set could be made arbitrarily small. But at the
same time the learned network also “learns” the noise present in the training set, so the error on
the test set usually starts increasing after the network size reaches a limit. Besides, the larger
networks are trained much longer than the smaller ones, so it is reasonable to pre-process the data,
using cv::PCA or similar technique, and train a smaller network on only essential features.

Another MLP feature is an inability to handle categorical data as is. However, there is a
workaround. If a certain feature in the input or output (in case of n -class classifier for
\fKaTeX parse error: Undefined control sequence: \f at position 4: n>2\?f? ) layer is categorical and can take \fKaTeX parse error: Undefined control sequence: \f at position 4: M>2\?f? different values, it makes sense to
represent it as a binary tuple of M elements, where the i -th element is 1 if and only if the
feature is equal to the i -th value out of M possible. It increases the size of the input/output
layer but speeds up the training algorithm convergence and at the same time enables “fuzzy” values
of such variables, that is, a tuple of probabilities instead of a fixed value.

ML implements two algorithms for training MLP’s. The first algorithm is a classical random
sequential back-propagation algorithm. The second (default) one is a batch RPROP algorithm.

@sa cv::ml::ANN_MLP

10、Logistic Regression (邏輯回歸)

ML implements logistic regression, which is a probabilistic classification technique. Logistic
Regression is a binary classification algorithm which is closely related to Support Vector Machines
(SVM). Like SVM, Logistic Regression can be extended to work on multi-class classification problems
like digit recognition (i.e. recognizing digits like 0,1 2, 3,… from the given images). This
version of Logistic Regression supports both binary and multi-class classifications (for multi-class
it creates a multiple 2-class classifiers). In order to train the logistic regression classifier,
Batch Gradient Descent and Mini-Batch Gradient Descent algorithms are used (see
http://en.wikipedia.org/wiki/Gradient_descent_optimization). Logistic Regression is a
discriminative classifier (see http://www.cs.cmu.edu/~tom/NewChapters.html for more details).
Logistic Regression is implemented as a C++ class in LogisticRegression.

In Logistic Regression, we try to optimize the training parameter \fKaTeX parse error: Undefined control sequence: \f at position 7: \theta\?f? such that the
hypothesis \fKaTeX parse error: Undefined control sequence: \f at position 26: …theta(x) \leq 1\?f? is achieved. We have \fKaTeX parse error: Undefined control sequence: \f at position 29: … g(h_\theta(x))\?f?
and \fKaTeX parse error: Undefined control sequence: \f at position 26: …ac{1}{1+e^{-z}}\?f? as the logistic or sigmoid function. The term “Logistic” in
Logistic Regression refers to this function. For given data of a binary classification problem of
classes 0 and 1, one can determine that the given data instance belongs to class 1 if \fKaTeX parse error: Undefined control sequence: \f at position 21: …eta(x) \geq 0.5\?f? or class 0 if \fKaTeX parse error: Undefined control sequence: \f at position 18: …\theta(x) < 0.5\?f? .

In Logistic Regression, choosing the right parameters is of utmost importance for reducing the
training error and ensuring high training accuracy:

  • The learning rate can be set with @ref cv::ml::LogisticRegression::setLearningRate “setLearningRate”
    method. It determines how fast we approach the solution. It is a positive real number.

  • Optimization algorithms like Batch Gradient Descent and Mini-Batch Gradient Descent are supported
    in LogisticRegression. It is important that we mention the number of iterations these optimization
    algorithms have to run. The number of iterations can be set with @ref
    cv::ml::LogisticRegression::setIterations “setIterations”. This parameter can be thought
    as number of steps taken and learning rate specifies if it is a long step or a short step. This
    and previous parameter define how fast we arrive at a possible solution.

  • In order to compensate for overfitting regularization is performed, which can be enabled with
    @ref cv::ml::LogisticRegression::setRegularization “setRegularization”. One can specify what
    kind of regularization has to be performed by passing one of @ref
    cv::ml::LogisticRegression::RegKinds “regularization kinds” to this method.

  • Logistic regression implementation provides a choice of 2 training methods with Batch Gradient
    Descent or the MiniBatch Gradient Descent. To specify this, call @ref
    cv::ml::LogisticRegression::setTrainMethod “setTrainMethod” with either @ref
    cv::ml::LogisticRegression::BATCH “LogisticRegression::BATCH” or @ref
    cv::ml::LogisticRegression::MINI_BATCH “LogisticRegression::MINI_BATCH”. If training method is
    set to @ref cv::ml::LogisticRegression::MINI_BATCH “MINI_BATCH”, the size of the mini batch has
    to be to a positive integer set with @ref cv::ml::LogisticRegression::setMiniBatchSize
    “setMiniBatchSize”.

A sample set of training parameters for the Logistic Regression classifier can be initialized as follows:
@snippet samples/cpp/logistic_regression.cpp init

@sa cv::ml::LogisticRegression


本專欄所有完整的代碼將在我的GitHub倉庫上更新,歡迎大家前往學習:

  • https://github.com/Keyird/OpenCV4-Machine-Learning

進入GitHub倉庫,點擊 star (紅色箭頭所示),第一時間獲取干貨:
在這里插入圖片描述

若想對每一種演算法實作進行更深入的了解,可以到OpenCV的如下目錄去閱讀原始碼,
在這里插入圖片描述

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/298199.html

標籤:其他

上一篇:[Java] 使用Android Studio撰寫Java測驗代碼

下一篇:OpenCV4機器學習(六):K-means原理及實作

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more