Created
August 28, 2012 09:29
-
-
Save mmitou/3496533 to your computer and use it in GitHub Desktop.
基本統計学 3.2 線形回帰 例3.2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Data.List | |
| data RegressionCalcTable = RegressionCalcTable { | |
| sumX :: Double, | |
| sumY :: Double, | |
| sumXX :: Double, | |
| sumXY :: Double, | |
| sumYY :: Double, | |
| elemNum :: Double | |
| } deriving (Show, Eq) | |
| -- table 3.2 | |
| height :: [Double] | |
| height = [171,180,169,173,173, | |
| 163,168,176,173,174, | |
| 164,171,172,172,175, | |
| 163,163,162,167,170, | |
| 173,170,170,175,170] | |
| weight :: [Double] | |
| weight = [62,71,53,78,59, | |
| 54,62,60,60,62, | |
| 50,66,69,63,62, | |
| 65,53,52,60,67, | |
| 70,67,56,68,56] | |
| average :: [Double] -> Double | |
| average [] = 0 | |
| average xs = (sum xs) / fromIntegral (length xs) | |
| calcTable :: [Double] -> [Double] -> RegressionCalcTable | |
| calcTable xs ys = RegressionCalcTable { | |
| sumX = sum xs, | |
| sumY = sum ys, | |
| sumXX = foldr (\x acc -> acc + x * x) 0 xs, | |
| sumXY = foldr (\(x,y) acc -> acc + x * y) 0 $ zip xs ys, | |
| sumYY = foldr (\y acc -> acc + y * y) 0 ys, | |
| elemNum = fromIntegral $ length xs | |
| } | |
| normalEquation :: RegressionCalcTable -> (Double, Double) | |
| normalEquation (RegressionCalcTable sx sy sxx sxy syy n) = (a, b) | |
| where | |
| a = (sxx * sy - sx * sxy) / (n * sxx - sx * sx) | |
| b = (n * sxy - sx * sy) / (n * sxx - sx * sx) | |
| linearRegression :: [Double] -> [Double] -> (Double -> Double) | |
| linearRegression xs ys = (\x -> a + b * x) | |
| where | |
| (a, b) = normalEquation $ calcTable xs ys |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
実行例
*Main> let f = linearRegression height weight
*Main> f 172
63.33125591669297
身長172cmはだいたい63.3kg