- 전체
- Native Apps
- WinJS App
- C# Apps
- XAML
- VB.net
- VisualC.net
- C++
- MFC
- visual studio mobile app dev
- Azure ms cloud service
- Asp.net
- 인공지능 (AI)
- wpf
- UWP
- MAUI
- asp.net
인공지능 (AI) [인공지능 VB.NET] Build Simple AI .NET Library - Part 2 - Machine Learning Introduction : 간단한 AI .NET 라이브러리 구축 - 2부 - 기계 학습 소개
2023.10.19 23:51
[인공지능 VB.NET] Build Simple AI .NET Library - Part 2 - Machine Learning Introduction : 간단한 AI .NET 라이브러리 구축 - 2부 - 기계 학습 소개
Build Simple AI .NET Library - Part 2 - Machine Learning Introduction

- Download LinearRegression sample - 298.2 KB LinearRegression.zip
- Download CommonLib - 5.3 MB CommonLib (1).zip
Series Introduction
This is the second article of creating .NET library. Below is link for Part 1:
My objective is to create a simple AI library that covers a couple of advanced AI topics such as Genetic algorithms, ANN, Fuzzy logics and other evolutionary algorithms. The only challenge to complete this series would be having enough time to work on code and articles.
Having the code itself might not be the main target however, understanding these algorithms is. Wish it will be useful to someone someday.
The series will be published in a couple of parts, I am not sure how many yet. Anyways, each part will focus on a single key topic trying to cover for good.
Please, feel free to comment and ask for any clarifications or hopefully suggest better approaches.
Article Introduction - Part 2 "Machine Learning Introduction"
I thought that it would be more beneficial to introduce separate article for basic definitions used in machine learning as we will use such definitions later in following articles.
Most of this article will be dedicated to the concept of ML and different terms, there are tons of online resources that can be referenced for further information.
What AI Really Means
Before discussion of ML, let's first define what AI really means and to consider AI definition as a starting point for way forward.
There are many definitions for AI based on application or problem being resolved, however the simplest definition to fit all could be "AI is the ability of creating machines that could take decisions without being explicitly programmed for" in other words "Building machines (or applications) that have some kind of self intelligence in form of taking decisions".
Here is a Wiki article about that.
The need for AI started when humans started to face very complicated problems that are very hard to be programmed in advance. For example, consider self driven vehicles. This is a very complicated task if the only approach is to program each and every scenario that a vehicle may face. Practically, this would be almost impossible.
Hence, clearly we need more special approaches (algorithms) that could impose some kind of intelligence to a vehicle's main processor.
Consider raising a baby, of course, at the beginning, you would explicitly guide and provide instructions however at some stage, due to human intelligence; the baby will start to learn from experience (whether good or bad experience), so learning is a very essential component to intelligence, and hence, an ML term is always associated with AI.
What Machine Learning Means
Simply, ML is an AI field that studies one problem "How machines or applications can auto-learn from experience?"
ML is a set of techniques, algorithms and/or tools used to form learning process and eventually AI portion of any machine.
Back to baby analogy, one way to teach a baby is by giving examples or putting him into an experience. same in ML, that is called "Supervised Learning" which means that we train a machine first by giving training sets.
Each training set shall be composed of the same set of inputs along with the correct answer (called label). Utilizing different algorithms, a machine can iterate through all training sets and start to learn and build AI then; shall be ready to predict (provide estimated output) for any similar number of inputs or take a decision.
But this is not the only type of ML, there are other two common types:
Unsupervised learning- in which there is no training set available, this is used for specific type of problems that will mention laterReinforced learning- is another type of ML, there is no training set, however machine will receive feedback based on accomplished target. for example, for AI application playing chess, feedback could be wining or losing the game.
Let's go through the details of each type and how it could be used.
Supervised Learning
Again, this is when we do have available training set that we use to train our machine (this is where term supervised is coming from). Maybe, this is the time to have real case example such as classical example of Building an application to estimate price of an apartment based on area.
This is a very classical example used in many AI references to explain the concept and I will use the same.
So, to build such an application, we will need a set of combinations representing flat area against price. Of course, real scenario price will have multiple factors, as location, number of rooms. However, for simplicity, we will consider other factors as constants and have no impact on price.
This is a supervised learning because we start with available data, and our target would be creating an application to learn from this data and even get more intelligent by having further experience (getting further combinations of area vs price).
Eventually, this application would expect inputs (flat area, single input) and predict output (price) which is a continuous number, these are the kinds of problems that are called "Regression" in AI.
You may think of regression as an optimization function or finding best-fit function mapping inputs to output. In algebra, there is a term called "Interpolation" which is mainly the same concept, finding a best-fit function for given set of inputs and outputs.
Of course, this mapping could be in linear or no-linear forms (based on complicity of problem). Linear regression is the simplest and it represents mapping function as linear or straight line. For AI terms, mapping function is called hypothesis or h function in form of h(x) = a + b * x where:
Xis the input(s)a & bare slope of the lineh(x)is the hypothesis function of inputs, or simply estimated output
Let's name the correct answer of any given training set as y, then error would be simply the difference between estimated answer (hypothesis) and correct answer e = h(x) - y.
Logically, this error shall be minimized as much as possible to ensure fulfilling best-fit part. Error minimization is a whole study area with many algorithms that I will continue discussion later at this article.
Now back to supervised learning, we have seen that regression is one application of supervised learning but it i s not the only one. Remember, regression works with continuous (or real) outputs. what about discrete outputs cases, for example, if we do have training set for couple of inputs and output is simply grouping the inputs to pre-defined groups or namely Classification which the second major utilization of supervised learning.
UnSupervised Learning
On the other hand, unsupervised learning does not have pre-given training set, just a set of inputs without labels (remember label is the correct answer) this kind of ML is used for specific set of problems where we cannot really label inputs or pre-program it. Let's have an example from social media. for example, recommendation list from YouTube or recommended friends from Facebook.
Unsupervised ML could be behind this kind of AI, where for each user; watch history or friend list are reviewed and sorted. This is called Clustering problems in AI. You can imagine that there is no way to program these recommendations for each user in advance.
Reinforced Learning
For the third type, it is some kind of special supervised version where machine learns from the outcome or simply its own experience. It is learning from the feedback of the output (as winning or loosing a game or reach a destination).
As an example, consider building application to play chess. from one end, there is no way to program all possible moves at any given time. and on the other end, if we managed to build the application to play each game and learn from winning or losing the game, then this is reinforced learning type.
What is Next
Above are mainly the fundamentals about ML and based on that, tons of algorithms and techniques are built to establish each type and solve different problems accordingly.
It is important to understand it as that will help in understanding any further advanced topics related to AI.
The next way forward would be exploring different algorithms and approaches, hopefully to understand AI further.
So this would be time to build our first AI algorithm with code.
Linear Regression Example
Let's create one application to solve a simple linear regression problem. Regardless of the technical background of the application or exact problem we are trying to resolve, the algorithm is always the same. Hence, we will not worry much about what this data is, but assume we got it somehow. Here is the data in hand:
Where X is the input (could be any real variable) and Y is the correct target or label. Plotting this data set will result in:
The objective of the application is to predict let's say output incase x is 70 based on given training set.
Based on the given data set, looks like linear regression would be an acceptable solution for this problem. Hence, the application will mainly resolve the hypothesis function h(x) = a + b * x , in other words, to find the values of a and b that yields to best fit line.
Let's build the algorithm for that, first will start with any random values of a and b.
''' <summary> ''' Linear Regression Pseudo Algorithm to resolve h(x) = a + b * x ''' 1- Start with random values for a and b ''' 2- Iterate through given training set, for each: ''' - Calculate h(x) ''' - Calculate error = h(x) - Y where y is the correct answer or label ''' 3- Sum all errors ''' </summary>
Now, we need to minimize error to the lowest possible value but first, let's get rid of -ve errors, errors can be in both directions positive or negative. One way to do so is by squaring the summation of error.
Some errors are higher than others based on the difference between correct answer and h(x) to ensure that most of the errors are targeted, let's take the average or mean of squared error which equals squared error/size of training set.
As per Statistics terms, this method is called "Mean Squared Error" or MSE and it tells you how close a regression line is to training set.

Some references, may refer to MSE as cost function which is a broader definition
Where m is the size of training set (how many training combinations)
As this is 2nd order polynomial equation (assuming one variable) so in 2D coordinates, this is the graph

From the above graph, clearly this function has only one min (we cannot tell by now where this min is). In other words, the above graph tells us that if we started with any random values for a and b, we will have an error anywhere on the above graph and from there, we need to move to min.
At the below graph, Blue point represents min error value, for any random a & b values we may end on right side (as red circle) or left side (as green circle).

The question is how to determine which side we are on the curve? right or left?
One way to determine direction is to draw a straight line that is touching with curve at the starting point and then calculate the slope of this line.

For example, a red line in the above graph has +ve slope (as moving to right, value on line increases) however green line has a -ve slope.
Let's revisit our pseudo algorithm:
''' <summary> ''' Linear Regression Pseudo Algorithm to resolve h(x) = a + b * x ''' 1- Start with random values for a and b ''' 2- Iterate through given training set, for each: ''' - Calculate h(x) ''' - Calculate error = h(x) - Y where y is the correct answer or label ''' 3- Sum all errors ''' 4- Calculate MSE (Mean Squared Error) = 1/2*training set size * sum of all errors ''' 5- Get slope of line touching curve at the current point (for each value of a and b) ''' - If +ve slope, move to left or Decrease a or b values ''' - If -ve slope, move to right or increase a or b values ''' 6- Repeat above steps from 2 to 5 till direction or slope of calculated line changes ''' 7- Last values for a and b are the optimal values as per MSE minimization ''' </summary>

Above is a very common and handy algorithm that is called Gradient Descent. However, the above version is valid mainly for linear regression, for nonlinear functions other considerations shall be taken.
So, how can we calculate the slope of a straight line?
Slope of line touching the function (curve) at certain point is exactly the definition of derivative of function. In our case, as we are having two variables (a & b), this is called a partial derivative.
Gradient Descent
So far, we have the following:



Let's start to resolve a:





To cut a long story short, here is the final partial derivative for a:

and here is for b:

Then:

To further control the step taken, let's add a small number representing the step size to take as fraction of slope. this is called "Learning Rate". Having improper value for learning rate can impact final behavior for our algorithm and we shall examine different values in our code.
Anyways, let's mark it as r:

similarly for b:

Above last 2 equations represent the final conclusion from applying Gradient Descent to linear regression.
Using the Code
To demonstrate the above, I have created a simple program:

The main function is Train, it accepts two 1D matrices representing training set:
Public Sub Train(_Inputs As Matrix1D, _Labels As Matrix1D) Dim m As Integer = _Inputs.Size ' Training set size Dim Err As Matrix1D ' represents sum of all errors in single iteration Dim Counter As Integer = 0 Dim Best_a, Best_b As Single If _Inputs.Size <> _Labels.Size Then Throw New Exception("Both Inputs and Labels Matrices sizes shall match.") End If ' Randomize a & b Randomize() ' Iterate and update a & b values till direction changes Do While Counter < 100 Dim h_Matrix As New Matrix1D(m) ' Calculate Error matrix Err = New Matrix1D(m) For I As Integer = 0 To m - 1 h_Matrix.SetValue(I, Hypothesis(_Inputs.GetValue(I))) Next Err = h_Matrix.Sub(_Labels) If CalcCostFunction(Err) < min_MSE OrElse Counter = 0 Then min_MSE = CalcCostFunction(Err) Best_a = a Best_b = b End If a = a - r * (1 / m) * Err.Sum Err = Err.Product(_Inputs) b = b - r * (1 / m) * Err.Sum Counter += 1 Loop a = Best_a b = Best_b End Sub
It implements pseudo algorithm of gradient descent.
There are different ways to terminate the iteration, I have selected one technique by setting max counter of 100 while keeping recording minimum MSE in each iteration along with Best_a and Best_b variables.
Lastly, I need to mention that sample software has reference to CommonLib which is added at the beginning of the article (the attached version is the most updated one).
Recap
We defined three types of ML:
Supervised learning- with available training set, mainly used for regression and classification problemsUnsupervised learning- no training set is available and is typically used for clustering problemsReinforced learning- where there is no training set, but the machine learns by outcome or feedback of every experience
Then, we have detailed one key Algorithm of Gradient Descent typically for linear regression giving 1 sample software.
I am not sure if the above was clear enough, please let me know.
Next Article
Mostly, it will be about the second use of supervised learning which is classification, typically using Perceptron.
History
- 10th September, 2017: Initial version
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
간단한 AI .NET 라이브러리 구축 - 2부 - 기계 학습 소개

시리즈 소개
.NET 라이브러리 만들기 두 번째 글입니다. 아래는 1부 링크입니다.
내 목표는 유전자 알고리즘, ANN, 퍼지 논리 및 기타 진화 알고리즘과 같은 몇 가지 고급 AI 주제를 다루는 간단한 AI 라이브러리를 만드는 것입니다. 이 시리즈를 완성하기 위한 유일한 과제는 코드와 기사 작업에 충분한 시간을 갖는 것입니다.
코드 자체를 갖는 것이 주요 목표는 아닐 수도 있지만 이러한 알고리즘을 이해하는 것이 주요 목표입니다. 언젠가 누군가에게 도움이 되었으면 좋겠습니다.
이 시리즈는 두 부분으로 나누어 출판될 예정인데, 아직 몇 부분인지는 잘 모르겠습니다. 어쨌든, 각 부분은 영원히 다루려고 노력하는 단일 핵심 주제에 중점을 둘 것입니다.
자유롭게 의견을 제시하고 설명을 요청하거나 더 나은 접근 방식을 제안해 주시기 바랍니다.
기사 소개 - 2부 "기계 학습 소개"
머신러닝에서 사용되는 기본 정의는 다음 글에서 사용할 예정이므로 별도의 글을 소개하는 것이 더 유익할 것이라고 생각했습니다.
이 기사의 대부분은 ML의 개념과 다양한 용어에 대해 다루며, 추가 정보를 참조할 수 있는 수많은 온라인 리소스가 있습니다.
AI가 실제로 의미하는 것
ML에 대해 논의하기 전에 먼저 AI가 실제로 무엇을 의미하는지 정의하고 AI 정의를 앞으로 나아갈 출발점으로 고려해 보겠습니다.
응용 프로그램이나 해결 중인 문제를 기반으로 AI에 대한 많은 정의가 있지만, 모든 것에 가장 적합한 가장 간단한 정의는 "AI는 명시적으로 프로그래밍하지 않고도 결정을 내릴 수 있는 기계를 만드는 능력입니다", 즉 "기계(또는 응용 프로그램)를 만드는 것입니다"라고 할 수 있습니다. ) 결정을 내리는 형태로 일종의 자기 지능을 가지고 있습니다."
여기 에 관한 Wiki 기사가 있습니다 .
AI의 필요성은 인간이 사전에 프로그래밍하기 매우 어려운 매우 복잡한 문제에 직면하기 시작했을 때 시작되었습니다. 예를 들어, 자율주행차를 생각해 보세요. 유일한 접근 방식이 차량이 직면할 수 있는 모든 시나리오를 프로그래밍하는 것이라면 이는 매우 복잡한 작업입니다. 현실적으로 이는 거의 불가능할 것이다.
따라서 차량의 메인 프로세서에 일종의 지능을 부여할 수 있는 보다 특별한 접근 방식(알고리즘)이 필요하다는 것은 분명합니다.
물론 아기를 키우는 것을 고려해보세요. 처음에는 명시적으로 안내하고 지시를 내리겠지만, 어떤 단계에서는 인간의 지능으로 인해; 아기는 경험(좋은 경험이든 나쁜 경험이든)을 통해 배우기 시작하므로 학습은 지능에 매우 필수적인 구성 요소이므로 ML 용어는 항상 AI와 연관됩니다.
머신러닝의 의미
간단히 말해서 ML은 "기계나 애플리케이션이 어떻게 경험을 통해 자동 학습할 수 있는가?"라는 한 가지 문제를 연구하는 AI 분야입니다.
ML은 학습 프로세스와 궁극적으로 모든 기계의 AI 부분을 형성하는 데 사용되는 일련의 기술, 알고리즘 및/또는 도구입니다.
아기 비유로 돌아가서, 아기를 가르치는 한 가지 방법은 예를 들거나 아기에게 경험을 제공하는 것입니다. ML에서도 마찬가지입니다. 이를 " Supervised Learning"라고 합니다. 이는 먼저 훈련 세트를 제공하여 기계를 훈련한다는 의미입니다.
각 훈련 세트는 정답(라벨이라고 함)과 함께 동일한 입력 세트로 구성됩니다. 다양한 알고리즘을 활용하여 기계는 모든 훈련 세트를 반복하고 AI를 학습하고 구축하기 시작할 수 있습니다. 유사한 수의 입력에 대해 예측(추정 출력 제공)하거나 결정을 내릴 준비가 되어 있어야 합니다.
그러나 이것이 ML의 유일한 유형은 아니며 다른 두 가지 일반적인 유형이 있습니다.
Unsupervised learning- 사용 가능한 훈련 세트가 없는 경우 나중에 언급할 특정 유형의 문제에 사용됩니다.Reinforced learning- 또 다른 유형의 ML입니다. 훈련 세트는 없지만 기계는 달성된 목표에 따라 피드백을 받습니다. 예를 들어 체스를 두는 AI 애플리케이션의 경우 피드백은 게임의 승리 또는 패배일 수 있습니다.
각 유형의 세부 사항과 사용 방법을 살펴 보겠습니다.
지도 학습
다시 말하지만, 이것은 기계를 훈련하는 데 사용할 수 있는 훈련 세트가 있는 때입니다(여기서 감독이라는 용어가 유래되었습니다). 아마도 면적을 기준으로 아파트 가격을 추정하는 애플리케이션을 구축하는 고전적인 예와 같은 실제 사례가 필요한 시점일 것입니다.
이것은 개념을 설명하기 위해 많은 AI 참고자료에서 사용되는 매우 고전적인 예이며 나도 동일한 예를 사용할 것입니다.
따라서 이러한 애플리케이션을 구축하려면 가격 대비 평평한 면적을 나타내는 일련의 조합이 필요합니다. 물론 실제 시나리오 가격에는 위치, 객실 수 등 여러 요소가 있습니다. 그러나 단순화를 위해 다른 요소를 상수로 간주하고 가격에 영향을 미치지 않습니다.
이는 사용 가능한 데이터로 시작하기 때문에 지도 학습입니다. 우리의 목표는 이 데이터에서 학습하고 더 많은 경험을 통해 더욱 지능적이 되는 애플리케이션을 만드는 것입니다(면적과 가격의 추가 조합 얻기).
Regression결국 이 애플리케이션은 입력(평평한 영역, 단일 입력)을 기대하고 연속적인 숫자인 출력(가격)을 예측하게 되는데, 이것이 AI에서 " "라고 불리는 종류의 문제입니다.
회귀를 최적화 함수로 생각하거나 입력을 출력으로 매핑하는 가장 적합한 함수를 찾는 것으로 생각할 수 있습니다. 대수학에는 주어진 입력 및 출력 세트에 가장 적합한 함수를 찾는 것과 주로 동일한 개념인 "보간"이라는 용어가 있습니다.
물론 이 매핑은 선형 또는 비선형 형태일 수 있습니다(문제의 복잡도에 따라). 선형 회귀는 가장 간단하며 매핑 기능을 선형 또는 직선으로 나타냅니다. AI 용어의 경우 매핑 함수를 가설 또는 h 함수라고 하며 h(x) = a + b * x 다음과 같은 형태입니다.
X입력입니다a & b선의 기울기입니다h(x)입력의 가설 함수 또는 단순히 추정된 출력입니다.
주어진 훈련 세트의 정답 이름을 로 지정하면 y오류는 단순히 예상 답변(가설)과 정답 간의 차이가 됩니다 e = h(x) - y.
논리적으로 가장 적합한 부품을 충족하려면 이 오류를 최대한 최소화해야 합니다. 오류 최소화는 이 기사의 뒷부분에서 계속 논의할 많은 알고리즘이 포함된 전체 연구 영역입니다.
이제 지도 학습으로 돌아가서 우리는 회귀가 지도 학습의 한 응용 프로그램이지만 이것이 유일한 응용 프로그램은 아니라는 것을 확인했습니다. 회귀는 연속(또는 실제) 출력에서 작동한다는 점을 기억하십시오. 예를 들어, 몇 가지 입력 및 출력에 대한 훈련 세트가 있는 경우 입력을 미리 정의된 그룹으로 그룹화하거나 지도 학습의 두 번째 주요 활용인 분류를 수행하는 경우 이산 출력의 경우는 어떻습니까?
비지도 학습
반면에 비지도 학습에는 미리 제공된 훈련 세트가 없으며 레이블이 없는 입력 세트만 있습니다(레이블이 정답임을 기억하세요). 이러한 종류의 ML은 실제로 입력 또는 사전에 레이블을 지정할 수 없는 특정 문제 세트에 사용됩니다. -프로그램해 보세요. 소셜 미디어의 예를 들어보겠습니다. 예를 들어 YouTube의 추천 목록이나 Facebook의 추천 친구 등이 있습니다.
감독되지 않은 ML은 이러한 종류의 AI 뒤에 있을 수 있습니다. 시청 기록이나 친구 목록을 검토하고 정렬합니다. 이를 AI에서는 클러스터링 문제라고 합니다. 각 사용자에 대해 이러한 권장 사항을 미리 프로그래밍할 방법이 없다고 상상할 수 있습니다.
강화 학습
세 번째 유형의 경우 기계가 결과 또는 단순히 자체 경험을 통해 학습하는 일종의 특별한 지도 버전입니다. 이는 결과(게임의 승리 또는 패배, 목적지 도달 등)의 피드백을 통해 학습하는 것입니다.
예를 들어, 체스를 두는 애플리케이션을 구축하는 것을 고려해 보세요. 한쪽 끝에서 주어진 시간에 가능한 모든 동작을 프로그래밍할 수 있는 방법은 없습니다. 반면에 각 게임을 플레이하고 게임의 승리 또는 패배를 통해 학습할 수 있는 애플리케이션을 구축했다면 이는 강화 학습 유형입니다.
다음은 무엇입니까
위에는 주로 ML에 대한 기본 사항이 있으며, 이를 기반으로 각 유형을 설정하고 그에 따라 다양한 문제를 해결하기 위해 수많은 알고리즘과 기술이 구축됩니다.
AI와 관련된 고급 주제를 이해하는 데 도움이 되므로 이를 이해하는 것이 중요합니다.
다음 단계는 AI를 더 깊이 이해하기 위해 다양한 알고리즘과 접근 방식을 탐색하는 것입니다.
이제 코드를 사용하여 첫 번째 AI 알고리즘을 구축할 때입니다.
선형 회귀 예
간단한 선형 회귀 문제를 해결하기 위해 하나의 애플리케이션을 만들어 보겠습니다. 애플리케이션의 기술적 배경이나 우리가 해결하려는 정확한 문제에 관계없이 알고리즘은 항상 동일합니다. 따라서 우리는 이 데이터가 무엇인지에 대해 크게 걱정하지 않고 어떻게든 얻은 것으로 가정합니다. 보유하고 있는 데이터는 다음과 같습니다.
X입력(실제 변수일 수 있음)은 어디에 있고 Y올바른 대상 또는 레이블은 무엇입니까? 이 데이터 세트를 플로팅하면 다음과 같은 결과가 발생합니다.
애플리케이션의 목적은 x주어진 훈련 세트를 기반으로 출력이 70일 경우를 예측하는 것입니다.
주어진 데이터 세트를 기반으로 볼 때 선형 회귀가 이 문제에 대해 허용 가능한 솔루션인 것처럼 보입니다. 따라서 응용 프로그램은 주로 가설 함수를 해결합니다 h(x) = a + b * x. 즉, 가장 적합한 선을 산출하는 a값 을 찾습니다.b
이에 대한 알고리즘을 구축해 보겠습니다. 먼저 a및 의 임의의 값으로 시작합니다 b.
''' < 요약 > ''' h(x) = a + b * x를 해결하기 위한 선형 회귀 의사 알고리즘 ''' 1- a와 b에 대한 임의의 값으로 시작 ''' 2- 주어진 훈련 세트를 반복합니다. 각각: ''' - h(x) 계산 ''' - 오류 계산 = h(x) - Y 여기서 y는 정답 또는 레이블 ''' 3- 모든 오류 합계 ''' < /summary >
이제 오류를 가능한 가장 낮은 값으로 최소화해야 합니다. 하지만 먼저 -ve 오류를 제거해 보겠습니다. 오류는 양수 또는 음수 방향으로 발생할 수 있습니다. 이를 수행하는 한 가지 방법은 오류의 합을 제곱하는 것입니다.
일부 오류는 정답과 h(x)의 차이를 기반으로 다른 오류보다 높습니다. 대부분의 오류가 대상이 되도록 보장하기 위해 제곱 오류/훈련 세트 크기와 동일한 제곱 오류의 평균 또는 평균을 취하겠습니다.
Mean Squared Error통계 용어에 따르면 이 방법은 " "라고 불리며 MSE회귀선이 훈련 세트에 얼마나 가까운지 알려줍니다.

일부 참고 자료에서는 MSE를 더 넓은 정의인 비용 함수로 참조할 수 있습니다.
훈련 세트의 크기는 어디에 m있습니까(훈련 조합 수)
이것은 2 차 다항식이므로(변수를 1개 가정) 2차원 좌표에서는 그래프가 됩니다.

위 그래프에서 이 함수에는 단 하나의 min만 있음이 분명합니다(지금은 이 min이 어디에 있는지 알 수 없습니다). 즉, 위 그래프는 a 및 에 대한 임의의 값으로 시작하면 b위 그래프의 어느 곳에서나 오류가 발생하고 거기에서 min으로 이동해야 함을 알려줍니다.
아래 그래프에서 파란색 점은 최소 오류 값을 나타내며 임의의 a& b값은 오른쪽(빨간색 원) 또는 왼쪽(녹색 원)에서 끝날 수 있습니다.

문제는 우리가 곡선에서 어느 쪽에 있는지 어떻게 결정하는가 하는 것입니다. 오른쪽 또는 왼쪽?
방향을 결정하는 한 가지 방법은 시작점에서 곡선과 접촉하는 직선을 그린 다음 이 선의 기울기를 계산하는 것입니다.

예를 들어, 위 그래프의 빨간색 선은 +ve 기울기(오른쪽으로 갈수록 선의 값이 증가함)를 갖지만 녹색 선은 -ve 기울기를 갖습니다.
의사 알고리즘을 다시 살펴보겠습니다.
''' < 요약 > ''' h(x) = a + b * x를 해결하기 위한 선형 회귀 의사 알고리즘 ''' 1- a와 b에 대한 임의의 값으로 시작 ''' 2- 주어진 훈련 세트를 반복합니다. 각각: ''' - h(x) 계산 ''' - 오류 계산 = h(x) - Y 여기서 y는 정답 또는 레이블입니다. '' ' 3- 모든 오류 합계 ''' 4- MSE 계산(평균 제곱 오류) = 1/2*훈련 세트 크기 * 모든 오류의 합 ''' 5- 현재 지점에서 곡선과 만나는 선의 기울기를 구합니다(a와 b의 각 값에 대해) ''' - 기울기가 +ve인 경우 다음으로 이동합니다. 왼쪽 또는 a 또는 b 값 감소 ''' - -ve 기울기인 경우 오른쪽으로 이동하거나 a 또는 b 값 증가 ''' 6- 계산된 선의 방향 또는 기울기가 변경될 때까지 위의 2~5 단계를 반복합니다 ''' 7- a와 b의 마지막 값은 MSE 최소화 ''' 에 따른 최적의 값입니다. < /summary >

위는 Gradient Descent 라고 하는 매우 일반적이고 편리한 알고리즘입니다 . 그러나 위 버전은 주로 선형 회귀에 유효하며, 비선형 함수의 경우 다른 사항을 고려해야 합니다.
그렇다면 직선의 기울기는 어떻게 계산할 수 있을까요?
특정 지점에서 함수(곡선)에 닿는 선의 기울기가 바로 함수미분의 정의입니다. a우리의 경우에는 두 개의 변수( & ) 가 있으므로 b이를 편도함수라고 합니다.
경사하강법
지금까지 우리는 다음을 가지고 있습니다:



해결을 시작해 보겠습니다 a.





간단히 말해서 다음은 최종 편미분입니다 a.

여기에 대한 내용은 다음과 같습니다 b.

그 다음에:

취해진 단계를 추가로 제어하려면 기울기의 비율로 취할 단계 크기를 나타내는 작은 숫자를 추가해 보겠습니다. 이것을 " 학습률 "이라고 합니다. 학습률에 부적절한 값이 있으면 알고리즘의 최종 동작에 영향을 미칠 수 있으므로 코드에서 다른 값을 조사하겠습니다.
어쨌든 다음과 같이 표시해 보겠습니다 r.

마찬가지로 b:

위의 마지막 2개 방정식은 경사하강법을 선형 회귀에 적용한 최종 결론을 나타냅니다.
코드 사용
위 내용을 보여주기 위해 간단한 프로그램을 만들었습니다.

주요 기능은 Train훈련 세트를 나타내는 두 개의 1D 행렬을 허용하는 것입니다.
Public Sub Train(_Inputs As Matrix1D, _Labels As Matrix1D) Dim m As Integer = _Inputs.Size ' 훈련 세트 크기 Dim Err As Matrix1D ' 는 단일 반복의 모든 오류 합계를 나타냅니다. Dim Counter As Integer = 0 Dim Best_a, Best_b As Single If _Inputs.Size <> _Labels.Size Then 새로운 예외 발생 ( " 입력과 레이블 행렬 크기가 모두 일치해야 합니다." ) End If ' a & b 무작위화 무작위화() ' 방향이 바뀔 때까지 a 및 b 값을 반복하고 업데이트합니다. Do While Counter < 100 Dim h_Matrix As New Matrix1D(m) ' 오류 행렬 계산 Err = New Matrix1D(m) For I As Integer = 0 To m - 1 h_Matrix.SetValue(I, 가설(_Inputs.GetValue(I))) 다음 오류 = h_Matrix. Sub (_Labels) CalcCostFunction (Err) < min_MSE OrElse 카운터 = 0 이면 min_MSE = CalcCostFunction(Err) 최고_a=a 최고_b=b 종료 If a = a - r * ( 1 / m) * Err.Sum 오류 = 오류.제품(_입력) b = b - r * ( 1 / m) * Err.Sum 카운터 += 1 루프 a = 최고_a b = 최고_b 서브 끝
경사하강법의 의사 알고리즘을 구현합니다.
Best_a반복을 종료하는 방법에는 여러 가지가 있습니다. 저는 및 Best_b변수 와 함께 각 반복에서 최소 MSE를 기록하면서 최대 카운터를 100으로 설정하는 기술을 하나 선택했습니다 .
CommonLib마지막으로 샘플 소프트웨어에 대한 참조가 기사 시작 부분에 추가되어 있다는 점을 언급해야 합니다 (첨부된 버전이 가장 업데이트된 버전입니다).
요약
우리는 세 가지 유형의 ML을 정의했습니다.
Supervised learning- 주로 회귀 및 분류 문제에 사용되는 사용 가능한 훈련 세트 포함Unsupervised learning- 훈련 세트를 사용할 수 없으며 일반적으로 클러스터링 문제에 사용됩니다.Reinforced learning- 훈련 세트는 없지만 기계는 모든 경험의 결과나 피드백을 통해 학습합니다.
그런 다음 1개의 샘플 소프트웨어를 제공하는 선형 회귀에 일반적으로 사용되는 경사하강법의 핵심 알고리즘 하나를 자세히 설명했습니다.
위의 내용이 충분히 이해되었는지 잘 모르겠습니다. 알려주시기 바랍니다.
다음 기사
대부분은 일반적으로 Perceptron을 사용하는 분류인 지도 학습의 두 번째 사용에 관한 것입니다.
역사
- 2017년 9월 10 일 : 초기 버전
특허
이 기사는 관련 소스 코드 및 파일과 함께 The Code Project Open License(CPOL) 에 따라 라이센스가 부여됩니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
댓글 0
| 번호 | 제목 | 글쓴이 | 날짜 | 조회 수 |
|---|---|---|---|---|
| 2 | [VisualBasic] Windows 화면 보호기/절전 모드 방지 방법 | 졸리운_곰 | 2020.09.10 | 649 |
| 1 |
C++로 hello world 앱 만들기(Windows 10)
| 가을의곰 | 2017.06.18 | 432 |
27.1K
1.9K
35

