Skip to content

Instantly share code, notes, and snippets.

@ooltcloud
Created December 30, 2014 15:06
Show Gist options
  • Save ooltcloud/0f3faef5cbf28298b5a3 to your computer and use it in GitHub Desktop.
Save ooltcloud/0f3faef5cbf28298b5a3 to your computer and use it in GitHub Desktop.
簡易回帰分析
Public Class Regression
''' <summary>
''' 係数の取得
''' </summary>
Public Shared Function GetPolynomialCoefficients(y As Double(), x As Double(), degree As Integer) As Double()
Dim Ymax = y.GetUpperBound(0)
Dim Xmax = x.GetUpperBound(0)
Dim N = degree
' 二次元配列に移し替え
Dim matY(Ymax, 0) As Double
For i = 0 To Ymax
matY(i, 0) = y(i)
Next
' 次数に応じた x() の行列を作成
Dim matX(Xmax, N) As Double
For i = 0 To Xmax
For j = 0 To N
matX(i, j) = x(i) ^ j
Next
Next
' 回帰分析
Dim r = Analyze(matY, matX)
Return r
End Function
''' <summary>
''' 回帰分析
''' </summary>
Public Shared Function Analyze(matY As Double(,), matX As Double(,)) As Double()
Dim mat1 = Matrix.Transpose(matX)
Dim mat2 = Matrix.Multiply(mat1, matX)
Dim mat3 = Matrix.Multiply(mat1, matY)
Dim mat4 = Matrix.Inverse(mat2)
Dim mat5 = Matrix.Multiply(mat4, mat3)
Dim N = mat5.GetUpperBound(0)
Dim r(N) As Double
For i = 0 To N
r(i) = mat5(i, 0)
Next
Return r
End Function
End Class
' プロットデータ
Dim x() As Double = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Dim y() As Double = {5, 8, 7, 8, 9, 11, 9, 11, 13, 12}
' 回帰分析 (プロットデータから2次式の各係数を求める)
Dim r = Regression.GetPolynomialCoefficients(y, x, 2)
' 結果
Console.WriteLine("{2}x^2 + {1}x + {0}", r(0), r(1), r(2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment