[인공지능  VB.NET] Build Simple AI .NET Library - Part 1 - Basics First : 간단한 AI .NET 라이브러리 구축 - 1부 - 기본 사항 우선

Build Simple AI .NET Library - Part 1 - Basics First

10 Sep 2017CPOL5 min read 35.8K    1.6K    72  
Part 1 of a series of articles demonstrating .NET AI library from scratch
This is the first part of a multi-series article whose 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.

Series Introduction

My objective is to create a simple AI library that covers 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 working 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.

This series will be published in few parts, am not sure how many yet. Anyways, each part will focus on 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 1 "Basics"

This is Part 1 of multi-parts series, have dedicated it to cover basic library called "CommonLib" that contains fundamental classes as:

  • Graphics wrapper class called "Canvas"
  • Math wrapper classes to handle "Vector" & "Matrix" operations and other math operations
  • Random generator class "RandomFactory"

Each of the above classes shall be explained in details below.

1. Graphics Wrap Class Canvas

Graphics shall be used to test AI libraries will build and hence, had to create one wrap class to contain all common graphics operations and make it easier than creating Graphics objects.

Canvas class wraps some graphics operations as DrawLineDrawBox (Square), DrawCircleDrawText and Clear.

Mainly, it contains one internal graphics object g and bitmap object bmp.

Constructor

VB.NET
''' <summary>
''' Canvas constructor function
''' </summary>
''' <param name="_width">Drawing area - Width</param>
''' <param name="_height">Drawing area - Height</param>
Public Sub New(_width As Integer, _height As Integer)
    Me._Width = _width
    Me._Height = _height
    Me._bmp = New Bitmap(_width, _height)
    g = Graphics.FromImage(_bmp)
    g.SmoothingMode = SmoothingMode.HighQuality
End Sub

Width & Height are mandatory integers to create Canvas object which represents drawing area.

Here is an example of declaring canvas object and how to use it.

VB.NET
Imports CommonLib.CommonLib

Public Class Form1
    ' Form-level Canvas object
    Private myCanvas As Canvas

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        myCanvas = New Canvas(PictureBox1.Width, PictureBox1.Height)
        Draw()
    End Sub

    Private Sub Draw()
        With myCanvas
            .DrawBox(50, 25, 25, Color.Black)
            .FillBox(50, 100, 25, Color.Red)
            .DrawCircle(50, 100, 200, Color.Blue)
            .FillCircle(50, 200, 200, Color.Green)
            .DrawText("Test String", 250, 200, Color.Red)
        End With
        ' To draw canvas
        PictureBox1.Image = myCanvas.Image
        ' other code
    End Sub

    Private Sub Clear()
        myCanvas.Clear()
        PictureBox1.Image = myCanvas.Image
    End Sub
End Class

and here is the result of the above code:

2. Math Classes

MathFunctions

This class wraps some useful math functions:

Constraint Function

VB.NET
''' <summary>
''' Constrains value between min and max values
'''   if less than min, return min
'''   more than max, return max
'''   otherwise return same value
''' </summary>
''' <param name="Value"></param>
''' <param name="min"></param>
''' <param name="max"></param>
''' <returns></returns>
Public Function Constraint(Value As Single, min As Single, max As Single) As Single
    If Value <= min Then
        Return min
    ElseIf Value >= max Then
        Return max
    End If
    Return Value
End Function

Map Function

VB.NET
''' <summary>
''' Re-maps a number from one range to another. In the example above,
''' </summary>
''' <param name="value"> the incoming value to be converted </param>
''' <param name="start1"> lower bound of the value's current range </param>
''' <param name="stop1"> upper bound of the value's current range </param>
''' <param name="start2"> lower bound of the value's target range </param>
''' <param name="stop2"> upper bound of the value's target range </param>
Public Shared Function Map(ByVal value As Single, ByVal start1 As Single, _
  ByVal stop1 As Single, ByVal start2 As Single, ByVal stop2 As Single) As Single
    Dim Output As Single = start2 + (stop2 - start2) * ((value - start1) / _
                           (stop1 - start1))
    Dim errMessage As String = Nothing
    
    If Output <> Output Then
        errMessage = "NaN (not a number)"
        Throw New Exception(errMessage)
    ElseIf Output = Single.NegativeInfinity _
                    OrElse Output = Single.PositiveInfinity Then
        errMessage = "infinity"
        Throw New Exception(errMessage)
    End If
    Return Output
End Function

Norm Function

VB.NET
''' <summary>
''' Normalizes a number from another range into a value between 0 and 1.
''' Identical to map(value, low, high, 0, 1);
''' Numbers outside the range are not clamped to 0 and 1, because
''' out-of-range values are often intentional and useful.
''' </summary>
''' <param name="value"> the incoming value to be converted </param>
''' <param name="start"> lower bound of the value's current range </param>
''' <param name="stop"> upper bound of the value's current range </param>
Public Shared Function Norm(ByVal value As Single, _
                            ByVal start As Single, ByVal [stop] As Single) As Single
    Return (value - start) / ([stop] - start)
End Function

GetBitArray Function

VB.NET
''' <summary>
''' Generates 8 bit array of an integer, value from 0 to 255
''' </summary>
''' <param name="Value"></param>
''' <returns></returns>
Public Function GetBitArray(Value As Integer) As Integer()
    Dim Result(7) As Integer
    Dim sValue As String
    Dim cValue() As Char
    
    Value = Constraint(Value, 0, 255)
    sValue = Convert.ToString(Value, 2).PadLeft(8, "0"c)
    cValue = sValue.ToArray
    For i As Integer = 0 To cValue.Count - 1
        If cValue(i) = "1"c Then
            Result(i) = 1
        Else
            Result(i) = 0
        End If
    Next
    Return Result
End Function

Matrix Operations

Matrix operations are very important (especially for ANN later) and hence it is worth creating a separate class(s) to handle different cases of matrix functions, namely, Vector and Matrix1D.

Lots of resources are available to describe matrices and its functions and hence, I will not spend much time on that.

Just need to mention that, two special matrices are only considered so far in CommonLibMatrix1D and Vector.

Matrix1D

Is single column-matrix:

Later, this class will help in simplifying neural network creation. This class implements IMatrix Interface.

  • Size - Size or Capacity of Matrix - Simply Number of Stored Elements in Values Array
  • Product - Implement Matrix Product function between 2 metrics, m1 and m2 or matrix and scalar
  • Add - Implement Matrix addition method between 2 metrics, m1 and m2 or matrix and scalar
  • Sub - Implement Matrix subtraction method between 2 metrics, m1 and m2 or matrix and scalar
  • Divide - Implement Matrix divide method between 2 metrics, m1 and m2 or matrix and scalar
  • Sum - Sum of all matrix elements a1+a2+a3+...........+an
  • RandomizeValues - Randomize matrix elements between min and max values
  • Copy - Copy contents of one matrix into object starting from given starting index
  • ForceValues - Forces all elements of matrix to ForcedValue
  • GetValue - Return index element of matrix Index starts with 0
  • SetValue - Set value of matrix element at position Index 0 indexed positions

Vector

Vector is a special matrix with 1 row and multiple columns (in our case, only 2 and 3 columns are considered not higher). This is one way to think about vectors, however the most efficient way is to consider a vector as "Magnitude plus Direction" object. This is a very powerful object and yet so much simple; just by giving 2 numbers, we may extract magnitude and direction.

Vectors play a very important rule in math and physics and maybe, I will have a separate article to cover vectors only. For now, you may visit this link to get more information about vectors and vectors operations.

Note: Only 2D and 3D vectors are considered in CommonLib, for higher dimensional vectors, matrix shall be used.

Many vector operations have been implemented in CommonLib such as:

  • Randomize - Randomize XY and Z components of vector between 0 and 1
  • Magnitude - Calculates the Euclidean magnitude (length) of the vector and returns the result = SQRT (X2+Y2+Z2)
  • Add - Adds xy, and z components to a vector, adds one vector to another, or adds two independent vectors together. Here is a graphical representation of vector addition from Wikipedia.

  • Sub - Perform vector subtraction with other vectors or scalar values:

  • Mult - Implements vector scalar multiplication
  • Div - Is scalar divide implementation
  • Distance - Calculates the Euclidean distance between two vectors = SQRT (dX2+dY2+dZ2)
  • Dot - Implements vectors dot product. More at this link.
  • Cross - Implements vectors cross product. Here is the link explaining the math behind it.
  • Normalize - Normalize the vector to length 1 (make it a unit vector).
  • Limit - Limit the magnitude of this vector to the value passed as max parameter.
  • SetMag - Set the magnitude of this vector to the value passed as len parameter.
  • Heading - Calculate the angle of rotation for this vector.
  • Rotate - Rotate the vector by an angle, magnitude remains the same.
  • AngleBetween - Calculates and returns the angle (in radians) between two vectors.

3. RandomFactory

This class is very important for both initialization of different AI objects and for test purposes. It extends .NET Random class and adds further methods:

It can provide different random functions in addition to numbers (integerSingle and Double), as Random Color, Random Character, Random Boolean.

In addition, it has an implementation for Gaussian random function using Box-Muller transform:

VB.NET
''' <summary>
'''   Generates normally distributed numbers using Box-Muller transform by 
'''   generating 2 random doubles
'''   Gaussian noise is statistical noise having a probability density function (PDF) 
'''   equal to that of the normal distribution, 
'''   which is also known as the Gaussian distribution.
'''   In other words, the values that the noise can take on are Gaussian-distributed.
''' </summary>
''' <param name = "Mean">Mean of the distribution, default = 0</param>
''' <param name = "StdDeviation">Standard deviation, default = 1</param>
''' <returns></returns>
Public Function NextGaussian(Optional ByVal Mean As Double = 0, _
                             Optional ByVal StdDeviation As Double = 1) As Double
    Dim X1 = _Gen.NextDouble()
    Dim X2 = _Gen.NextDouble()
    Dim StdDistribution = Math.Sqrt(-2.0 * Math.Log(X1)) * Math.Sin(2.0 * Math.PI * X2)
    Dim GaussianRnd = Mean + StdDeviation * StdDistribution
    
    Return GaussianRnd
End Function

Also, it implements Triangle distribution random generation (you may check this wiki article):

VB.NET
''' <summary>
'''   Generates values from a triangular distribution
'''   Triangular distribution is a continuous probability distribution with:
'''       lower limit a
'''       upper limit b 
'''       mode c
'''   where a less than b 
'''   c is higher than or equal a but less than or equal b
''' </summary>
''' <param name = "min">Minimum</param>
''' <param name = "max">Maximum</param>
''' <param name = "mode">Mode (most frequent value)</param>
''' <returns></returns>
Public Function NextTriangular(ByVal min As Double, ByVal max As Double, _
                               ByVal mode As Double) As Double
    Dim u = _Gen.NextDouble()
    
    If (u < (mode - min) / (max - min)) Then
        Return min + Math.Sqrt(u * (max - min) * (mode - min))
    Else
        Return max - Math.Sqrt((1 - u) * (max - min) * (max - mode))
    End If
End Function

Shuffle method provides random shuffle implementation for a list by using the Fisher-Yates/Knuth algorithm:

VB.NET
''' <summary>
'''   Shuffles a list in O(n) time by using the Fisher-Yates/Knuth algorithm
''' </summary>
''' <param name = "list"></param>
Public Sub Shuffle(ByVal list As IList)
    For i = 0 To list.Count - 1
        Dim j = _Gen.Next(0, i + 1)
        
        Dim temp = list(j)
        list(j) = list(i)
        list(i) = temp
    Next i
End Sub

To get efficient result of RandomFactory class, a global or form level object shall be created and used through out the code.

What is Next

The next article will be about Genetic Algorithms (might be fuzzy controller!) depends on which code shall be ready first.

To Do List

  1. Add 2D Matrix operations implementation. 1D matrix is good for now, however extend library to include 2D shall add more efficiency or practicality. I wish to complete this task before starting ANN library.

History

  • CommonLib has been built to act as supporting class library for different projects, hence it shall be kept as a separate solution and only add references.

Version 1 of this library is completed by August 2017, expecting further versions to follow.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

 

Written By
Engineer
Egypt Egypt
Electrical engineer, programmer on my free time.

 

 

간단한 AI .NET 라이브러리 구축 - 1부 - 기본 사항 우선

2017년 9월 10일CPOL5분 읽기35.8K   1.6K   72  
.NET AI 라이브러리를 처음부터 시연하는 기사 시리즈 중 1부
이것은 유전자 알고리즘, ANN, 퍼지 논리 및 기타 진화 알고리즘과 같은 몇 가지 고급 AI 주제를 다루는 간단한 AI 라이브러리를 만드는 것이 목표인 다중 시리즈 기사의 첫 번째 부분입니다.

시리즈 소개

내 목표는 유전자 알고리즘, ANN, 퍼지 논리 및 기타 진화 알고리즘과 같은 몇 가지 고급 AI 주제를 다루는 간단한 AI 라이브러리를 만드는 것입니다. 이 시리즈를 완성하기 위한 유일한 과제는 코드와 기사 작업에 충분한 시간을 투자하는 것입니다.

코드 자체를 갖는 것이 주요 목표는 아닐 수도 있지만 이러한 알고리즘을 이해하는 것이 주요 목표입니다. 언젠가 누군가에게 도움이 되었으면 좋겠습니다.

이 시리즈는 몇 부분으로 나누어 출판될 예정이며, 아직 몇 부분인지는 확실하지 않습니다. 어쨌든, 각 부분은 좋은 점을 다루기 위해 단일 핵심 주제에 중점을 둘 것입니다.

자유롭게 의견을 제시하고 설명을 요청하거나 더 나은 접근 방식을 제안해 주시기 바랍니다.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

기사 소개 - 1부 "기본 사항"

이것은 여러 부분으로 구성된 시리즈의 1부이며 CommonLib다음과 같은 기본 클래스를 포함하는 " "라는 기본 라이브러리를 다루는 데 전념했습니다.

  • Canvas' ' 이라는 그래픽 래퍼 클래스
  • Vector" " & " Matrix" 연산 및 기타 수학 연산을 처리하는 수학 래퍼 클래스
  • 무작위 생성기 클래스 " RandomFactory"

위의 각 클래스에 대해서는 아래에서 자세히 설명합니다.

1. 그래픽 랩 클래스 캔버스

그래픽은 빌드할 AI 라이브러리를 테스트하는 데 사용되므로 모든 일반적인 그래픽 작업을 포함하고 Graphics개체를 만드는 것보다 쉽게 ​​만들기 위해 하나의 랩 클래스를 만들어야 했습니다.

Canvas클래스는 일부 그래픽 작업을 DrawLineDrawBoxSquare), DrawCircle및 DrawText로 래핑합니다 Clear.

g주로 하나의 내부 그래픽 객체 와 비트맵 객체를 포함합니다 bmp.

건설자

VB.NET
''' < 요약 > ''' 캔버스 생성자 함수
 ''' < /summary > ''' < param name="_width" > 그리기 영역 - 너비 < /param > ''' < param name="_height" > 그리기 Area - Height < /param > Public Sub New (_width As Integer , _height As Integer )
     Me ._Width = _width
     Me ._Height = _height
     Me ._bmp =  비트맵(_width, _height) 
 
  
  
    
    g = 그래픽.FromImage(_bmp)
    g.SmoothingMode = SmoothingMode.HighQuality
 서브 

Width& 는 도면 영역을 나타내는 객체를 Height생성하는 데 필요한 필수 정수입니다 .Canvas

canvas다음은 객체 선언 및 사용 방법 의 예입니다 .

VB.NET
CommonLib.CommonLib을 가져옵니다.

Public  Class Form1
     ' 양식 수준 Canvas 객체 
    Private myCanvas As Canvas

    Private  Sub Form1_Load(sender As  Object , e As EventArgs)는 MyBase .Load를 처리합니다 . 
        myCanvas =  캔버스(PictureBox1.Width, PictureBox1.Height)
        그리다()
     서브 

     myCanvas를 사용한 비공개 하위 그리기()
        
            .DrawBox( 50 , 25 , 25 , 색상.검정색)
            .FillBox( 50 , 100 , 25 , 색상.빨간색)
            .DrawCircle( 50 , 100 , 200 , 색상.블루)
            .FillCircle( 50 , 200 , 200 , 색상.녹색)
            .DrawText( " Test String" , 250 , 200 , Color.Red)
         End  With 
        ' 캔버스를 그리려면
        PictureBox1.Image = myCanvas.Image
        ' 다른 코드 
    End  Sub

    비공개  서브 클리어()
        myCanvas.Clear()
        PictureBox1.Image = myCanvas.Image
    종료  하위 
종료  클래스

위 코드의 결과는 다음과 같습니다.

2. 수학 수업

수학 함수

이 클래스는 몇 가지 유용한 수학 함수를 래핑합니다.

제약 기능

VB.NET
''' < 요약 > ''' 최소값과 최대값 사이의 값을 제한합니다.
 ' ''    min보다 작으면 min을 반환하고,
    max보다 크면 min을 반환하고, max를 반환하고, max
 를 반환합니다. '''    그렇지 않으면 동일한 값을 반환합니다.
 ''' < /summary > ' '' < param name="값" > < /param > ''' < param name="min" > < /param > ''' < param name="max" > < /param > ''' < 반환 > < /returns > 공용 함수 제약 조건(Value As Single , min As Single , max As Single ) As Single If Value <= min Then Return min
     ElseIf Value >= max Then Return max
     End If Return Value
 End Function 
 
  
  
  
 
     
    
        
         
     

지도 기능

VB.NET
''' < 요약 > ''' 한 범위의 숫자를 다른 범위로 다시 매핑합니다. 위의 예에서
 ''' < /summary > ''' < param name="value" > 변환할 들어오는 값 < /param > ''' < param name="start1" > 값의 현재 하한값 range < /param > ''' < param name="stop1" > 값 현재 범위의 상한 < /param > ''' < param name="start2" > 값 대상 범위의 하한 < /param > ' '' < param name="stop2" > 값의 대상 범위 상한 < /param > 공용 공유 함수 맵( ByVal value As Single , ByVal start1 As Single , _
   ByVal stop1 As Single , ByVal start2 As Single , ByVal stop2 As Single ) As Single Dim 출력 As Single = start2 + (stop2 - start2) * ((value - start1) / _ 
 
  
  
  
  
  
        
     
                           (정지1 - 시작1))
    Dim errMessage As  String = 아무것도 없음
    
    If Output <> Output Then 
        errMessage = " NaN (숫자 아님)" 
        Throw  New Exception(errMessage)
     ElseIf Output = Single .NegativeInfinity _
                     OrElse Output = Single .PositiveInfinity Then 
        errMessage = " infinity" 
        Throw  New Exception(errMessage)
     End  If 
    Return 출력
 종료  기능

노름 함수

VB.NET
''' < 요약 > ''' 다른 범위의 숫자를 0과 1 사이의 값으로 정규화합니다.
 ''' map(value, low, high, 0, 1)과 동일합니다.
''' 범위 밖의 숫자는 0과 1로 고정되지 않습니다.
 ''' 범위를 벗어난 값은 종종 의도적이고 유용하기 때문입니다.
''' < /summary > ''' < param name="value" > 변환할 들어오는 값 < /param > ''' < param name="start" > 값 현재 범위의 하한 < /param > ''' < param name="stop" > 값의 현재 범위 상한 < /param > 공용 공유 함수 Norm( ByVal value As Single , _
                             ByVal start As Single , ByVal [ stop ] As Single ) As Single 반환 (값 - 시작) / ([ 중지 ] - 시작)
 종료 기능 
 
  
  
  
      
     

GetBitArray 함수

VB.NET
''' < 요약 > ''' 0에서 255 사이의 값인 정수의 8비트 배열을 생성합니다. '
 '' < /summary > ''' < param name="Value" > < /param > ''' < return > < / returns > 공용 함수 GetBitArray(정수형 값 ) As Integer ( )
     Dim Result( 7 ) As Integer Dim sValue As String Dim cValue() As Char 
 
  
 
    
     
     
    
    값 = 제약조건(값, 0 , 255 )
    sValue = Convert.ToString(Value, 2 ).PadLeft( 8 , " 0" c)
    cValue = sValue.ToArray
    For i As  Integer = 0  To cValue.Count - 1 
        If cValue(i) = " 1" c Then 
            Result(i) = 1 
        Else 
            Result(i) = 0 
        End  If 
    Next 
    반환 결과
 End  Function

매트릭스 연산

Vector행렬 연산은 매우 중요하므로(특히 이후 ANN의 경우) 행렬 함수의 다양한 경우를 처리하기 위해 별도의 클래스, 즉 및 를 만드는 것이 좋습니다 Matrix1D.

행렬과 그 기능을 설명하는 데 사용할 수 있는 리소스가 많이 있으므로 이에 대해 많은 시간을 투자하지 않겠습니다.

단지 두 가지 특별한 행렬이 지금까지 에서만 고려되었다는 점을 언급할 필요가 있습니다 CommonLibMatrix1D그리고 Vector.

매트릭스1D

단일 열 행렬입니다.

나중에 이 클래스는 신경망 생성을 단순화하는 데 도움이 될 것입니다. 이 클래스는 IMatrix인터페이스를 구현합니다.

  • Size- 행렬의 크기 또는 용량 - 단순히 값 배열에 저장된 요소 수
  • Productm1- 2개의 메트릭 , m2행렬과 스칼라 간의 행렬 곱 기능 구현
  • Addm1- 2개의 메트릭 , m2행렬과 스칼라 간의 행렬 추가 방법 구현
  • Subm1- 2개의 메트릭 , m2행렬과 스칼라 간의 행렬 빼기 방법 구현
  • Dividem1- 2개의 메트릭 , m2행렬과 스칼라 간의 행렬 나누기 방법을 구현합니다.
  • Sum- 모든 행렬 요소의 합 a 1 +a 2 +a 3 +...........+ an
  • RandomizeValues- 최소값과 최대값 사이에서 행렬 요소를 무작위화합니다.
  • Copy- 주어진 시작 인덱스부터 시작하여 하나의 행렬의 내용을 객체에 복사합니다.
  • ForceValues- 행렬의 모든 요소를 ​​강제로ForcedValue
  • GetValue- 행렬의 반환 인덱스 요소는 Index다음으로 시작합니다.0
  • SetValueIndex 0- 위치 인덱스 위치 에서 행렬 요소의 값 설정

벡터

Vector1개의 행과 여러 개의 열이 있는 특수 행렬입니다(이 경우 2개와 3개의 열만 더 높지 않은 것으로 간주됩니다). 이는 벡터에 대해 생각하는 한 가지 방법이지만 가장 효율적인 방법은 vector"크기 + 방향" 개체를 고려하는 것입니다. 이것은 매우 강력한 개체이면서도 매우 단순합니다. 숫자 2개만 입력하면 크기와 방향을 추출할 수 있습니다.

벡터는 수학과 물리학에서 매우 중요한 규칙을 따르며 아마도 벡터에 대해서만 다루는 별도의 기사가 있을 것입니다. 지금은 이 링크를 방문하여 벡터 및 벡터 작업에 대한 자세한 정보를 얻을 수 있습니다.

참고 : 에서는 2D 및 3D 벡터만 고려되며 CommonLib, 더 높은 차원 벡터의 경우 매트릭스가 사용됩니다.

다음과 같은 많은 벡터 연산이 구현되었습니다 CommonLib.

  • RandomizeRandomize X및 Y사이 의 Z벡터 구성요소01
  • Magnitude- 벡터의 유클리드 크기(길이)를 계산하고 결과 = SQRT(X 2 +Y 2 +Z 2 ) 를 반환합니다.
  • Add벡터에 , 및 구성 요소를 추가하거나, 한 벡터를 다른 벡터에 추가하거나, 두 개의 독립 벡터를 함께 추가 x합니다 yz다음은 Wikipedia의 벡터 추가에 대한 그래픽 표현입니다.

  • Sub- 다른 벡터 또는 스칼라 값으로 벡터 빼기를 수행합니다.

  • Mult- 벡터 스칼라 곱셈을 구현합니다.
  • Div- 스칼라 분할 구현 여부
  • Distance- 두 벡터 사이의 유클리드 거리를 계산합니다 = SQRT (dX 2 +dY 2 +dZ 2 )
  • Dot- 벡터 내적을 구현합니다. 이 링크 에서 자세한 내용을 확인하세요 .
  • Cross- 벡터 외적을 구현합니다. 다음은 그 뒤에 있는 수학을 설명하는 링크 입니다 .
  • Normalize- 벡터를 길이 1로 정규화합니다(단위 벡터로 만듭니다).
  • Limit- 이 벡터의 크기를 매개변수로 전달된 값으로 제한합니다 max.
  • SetMag- 이 벡터의 크기를 매개변수로 전달된 값으로 설정합니다 len.
  • Heading- 이 벡터의 회전 각도를 계산합니다.
  • Rotate- 벡터를 각도만큼 회전해도 크기는 동일하게 유지됩니다.
  • AngleBetween- 두 벡터 사이의 각도(라디안 단위)를 계산하고 반환합니다.

3. 랜덤팩토리

이 클래스는 다양한 AI 객체의 초기화와 테스트 목적 모두에 매우 중요합니다. .NET 클래스를 확장 Random하고 추가 메서드를 추가합니다.

integer숫자( , Single외에 DoubleRandom Color, Random Character, Random Boolean 등 다양한 Random 기능을 제공할 수 있습니다.

또한 GaussianBox-Muller 변환을 사용하여 임의 함수를 구현합니다.

VB.NET
''' < 요약 > '' '    2개의 임의의 double을 생성하는
 '''    Box-Muller 변환을 사용하여 정규 분포 숫자를 생성합니다. ''' 
 가우스    잡음은 확률 밀도 함수(PDF) 
 '''    가 다음과 동일한 통계 잡음입니다. 정규 분포, 
 '''    가우스 분포라고도 알려져 있습니다.
'''    즉, 노이즈가 취할 수 있는 값은 가우스 분포입니다.
''' < /summary > ''' < param name = "Mean" > 분포 평균, 기본값 = 0 < /param > ''' < param name = "StdDeviation" > 표준 편차, 기본값 = 1 < /param > ''' < 반환 > < /returns > 공용 함수 NextGaussian( Optional ByVal Mean As Double = 0 , _
                              Optional ByVal StdDeviation As Double = 1 ) As Double Dim X1 = _Gen.NextDouble()
     Dim X2 = _Gen.NextDouble()
     Dim StdDistribution = Math.Sqrt(-2.0 * Math.Log(X1)) * Math.Sin( 2 . 0 * Math.PI * X2)
     Dim GaussianRnd = 평균 + StdDeviation * StdDistribution 
 
    
    
 
      
    
    
    GaussianRnd
 종료  함수 반환

또한 분포 무작위 생성을 구현합니다 ( 이 위키 기사를Triangle 확인할 수 있습니다 ).

VB.NET
''' < 요약 > '''    삼각 분포에서 값을 생성합니다
 . '''    삼각 분포는 다음을 갖는 연속 확률 분포입니다.
 '''        하한 a
 '''        상한 b 
 '''        모드 c
 '''    여기서 a는 더 적습니다. b보다 
 '''    c는 a보다 높거나 같지만 b보다 작거나 같습니다.
 ''' < /summary > ''' < 매개변수 이름 = "min" > 최소값 < /param > ''' < 매개 변수 이름 = "max " > 최대 < /param > ''' < param name = "mode" > 모드(가장 빈번한 값) < /param > ''' < 반환 > < /returns > Public Function NextTriangular( ByVal min As Double , ByVal max As Double , _
                                ByVal 모드 As Double ) As Double Dim u = _Gen.NextDouble() 
 
    
    
    
 
     
    
    
    If (u < (mode - min) / (max - min)) Then 
        return min + Math.Sqrt(u * (max - min) * (mode - min))
     Else 
        Return max - Math.Sqrt(( 1 - u ) * (최대 - 최소) * (최대 - 모드))
     End  If 
End  함수

Shuffle메소드는 Fisher-Yates/Knuth 알고리즘을 사용하여 목록에 대한 무작위 순서 섞기 구현을 제공합니다.

VB.NET
''' < 요약 > '''    Fisher-Yates/Knuth 알고리즘을 사용하여 O(n) 시간에 목록을 섞습니다. ''
 ' < /summary > ''' < param name = "list" > < /param > Public Sub Shuffle( ByVal list As IList)
     For i = 0 To list.Count - 1 Dim j = _Gen. 다음 ( 0 , i + 1 ) 
 
    
  
        
        
        어두운 온도 = list(j)
        목록(j) = 목록(i)
        목록(i) = 임시
    다음 i
 End  Sub

효율적인 클래스 결과를 얻으려면 RandomFactory전역 또는 양식 수준 개체를 생성하여 코드 전체에서 사용해야 합니다.

다음은 무엇입니까

다음 기사는 어떤 코드가 먼저 준비되어야 하는지에 따라 유전 알고리즘(퍼지 컨트롤러일 수도 있음)에 관한 것입니다.

할 일 목록

  1. 2D 매트릭스 작업 구현을 추가합니다. 현재로서는 1D 매트릭스가 좋지만 2D를 포함하도록 라이브러리를 확장하면 효율성이나 실용성이 더 높아집니다. ANN 라이브러리를 시작하기 전에 이 작업을 완료하고 싶습니다.

역사

  • CommonLib다양한 프로젝트에 대한 지원 클래스 라이브러리 역할을 하도록 구축되었으므로 별도의 솔루션으로 유지하고 참조만 추가해야 합니다.

이 라이브러리의 버전 1은 2017년 8월까지 완료되었으며, 추가 버전이 나올 것으로 예상됩니다.

특허

이 기사는 관련 소스 코드 및 파일과 함께 The Code Project Open License(CPOL) 에 따라 라이센스가 부여됩니다.

 

작성자
엔지니어
이집트 이집트

 

자유시간에는 전기 기술자이자 프로그래머입니다.

 

 

 

 

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
122 [Windows Programming] 윈도우 스토어 앱 등록 방법 (단계별) - 앱 배포, 앱 출시, 앱 등록 [윈도우 스토어, 윈도 스토어(Windows Store)] file 졸리운_곰 2025.02.15 75
121 [asp.net] [ASP.NET Core] IIS 배포 (게시) file 졸리운_곰 2024.09.20 228
120 [WPF] Using Images in WPF TabControl Headers 탭컨트롤 헤더 이미지 file 졸리운_곰 2024.02.18 211
119 [Windows Apps][MFC] HTTP SPY : HTTP 스파이 file 졸리운_곰 2023.11.29 185
118 [Windows Apps][MFC] 2D LUA Based Robot Simulator : 2D LUA 기반 로봇 시뮬레이터 file 졸리운_곰 2023.11.29 183
117 [인공지능 VB.NET] Build Simple AI .NET Library - Part 2 - Machine Learning Introduction : 간단한 AI .NET 라이브러리 구축 - 2부 - 기계 학습 소개 file 졸리운_곰 2023.10.19 151
» [인공지능 VB.NET] Build Simple AI .NET Library - Part 1 - Basics First : 간단한 AI .NET 라이브러리 구축 - 1부 - 기본 사항 우선 file 졸리운_곰 2023.10.19 267
115 [Windows Programming] [VisualStudio] Nuget 패키지소스 URL file 졸리운_곰 2023.09.14 189
114 [Windows Programming] A brief history of Windows UI platforms : Windows UI 플랫폼의 간략한 역사 file 졸리운_곰 2023.09.04 159
113 [C# Apps] Editor3D: A Windows.Forms Render Control with interactive 3D Editor in C# Editor3D: C#의 대화형 3D 편집기가 포함된 Windows.Forms 렌더 컨트롤 file 졸리운_곰 2023.09.03 543
112 [인공지능 (AI)] Logo Recognition System file 졸리운_곰 2023.06.04 199
111 [C# app] Pythonnet – .NET Core와 Python의 간단한 결합 : Pythonnet – A Simple Union of .NET Core and Python You’ll Love file 졸리운_곰 2023.03.11 183
110 [C# app] Gidon C# 플러그인 프레임워크에 Python 애플리케이션 포함 : Embedding Python Applications within Gidon C# Plugin Framework file 졸리운_곰 2023.03.07 252
109 [C# App] Gidon - Avalonia 기반 MVVM 플러그인 IoC 컨테이너 : Gidon - Avalonia based MVVM Plugin IoC Container file 졸리운_곰 2023.03.07 168
108 [VS2019] [C#] WinForm에 MySQL 연동하기 file 졸리운_곰 2022.12.25 228
107 [윈도우즈 앱 개발]CaptureManager SDK - Capturing, Recording and Streaming Video and Audio from Web-Cams file 졸리운_곰 2021.04.13 264
106 [ASP.NET] JavaScript 및 ASP.NET 개발자를 위한 Blazor 소개 file 졸리운_곰 2021.03.28 297
105 [c# asp.net core] - gRPC 서버, 클라이언트 샘플 튜토리얼 file 졸리운_곰 2021.02.10 400
104 [C#] sqlite on C# 예제로 배우는 C# 프로그래밍 file 졸리운_곰 2021.01.30 401
103 윈도우 wcript.shell 졸리운_곰 2020.09.10 296
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED