「その問題、やっぱり数理モデルが解決します」を読んで、データ分析の勉強をしています。
回帰分析の詳しい方法は、書籍を読んでいただくのが良いかと思います。
ここでは、書籍で導出された式をC#で実装します。
線形回帰の問題は書籍の「第9章 売り上げを予測するには?」で挙げられており、以下の散布データを直線に近似する方法の説明がされています。
| x | y |
|---|---|
| 1 | 3 |
| 2 | 5 |
| 3 | 6 |
| 4 | 4 |
このデータをエクセルで散布図を描き、回帰直線を表示すると以下のようになります。
回帰直線は、以下のように定義します。
このaとbを求める式は以下となります。(導出方法は書籍を見てください。)
この式を使ってプログラムを書くと以下になります。
using System;
using System.Linq;
namespace SimpleRegressionAnalysis
{
class Program
{
//y = a + bx に回帰させる
static double calculateB(double [] x, double [] y, double average_x, double average_y) {
double denominator = 0;
foreach (double xi in x) {
denominator += Math.Pow(xi - average_x, 2);
}
double molecule = 0;
for (int i = 0; i < x.Length; ++i) {
molecule += (x[i] - average_x) * (y[i] - average_y);
}
return molecule / denominator;
}
static double calculateA(double b, double average_x, double average_y) {
return average_y - average_x * b;
}
static void Main(string[] args)
{
double[] x = new double[] {1, 2, 3, 4 };
double[] y = new double[] {3, 5, 6, 4 };
double average_x = x.Average();
double average_y = y.Average();
double b = calculateB(x, y, average_x, average_y);
double a = calculateA(b, average_x, average_y);
Console.WriteLine(String.Format("a = {0}, b = {1}", a, b));
}
}
}

0 件のコメント :
コメントを投稿