1 | // $Id: Linear.cc 703 2006-12-18 00:47:44Z jari $ |
---|
2 | |
---|
3 | /* |
---|
4 | Copyright (C) The authors contributing to this file. |
---|
5 | |
---|
6 | This file is part of the yat library, http://lev.thep.lu.se/trac/yat |
---|
7 | |
---|
8 | The yat library is free software; you can redistribute it and/or |
---|
9 | modify it under the terms of the GNU General Public License as |
---|
10 | published by the Free Software Foundation; either version 2 of the |
---|
11 | License, or (at your option) any later version. |
---|
12 | |
---|
13 | The yat library is distributed in the hope that it will be useful, |
---|
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
---|
16 | General Public License for more details. |
---|
17 | |
---|
18 | You should have received a copy of the GNU General Public License |
---|
19 | along with this program; if not, write to the Free Software |
---|
20 | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA |
---|
21 | 02111-1307, USA. |
---|
22 | */ |
---|
23 | |
---|
24 | #include "Linear.h" |
---|
25 | #include "yat/statistics/AveragerPair.h" |
---|
26 | #include "yat/utility/vector.h" |
---|
27 | |
---|
28 | #include <gsl/gsl_fit.h> |
---|
29 | |
---|
30 | namespace theplu { |
---|
31 | namespace yat { |
---|
32 | namespace regression { |
---|
33 | |
---|
34 | Linear::Linear(void) |
---|
35 | : OneDimensional(), alpha_(0), alpha_var_(0), beta_(0), beta_var_(0), |
---|
36 | mse_(0), m_x_(0) |
---|
37 | { |
---|
38 | } |
---|
39 | |
---|
40 | Linear::~Linear(void) |
---|
41 | { |
---|
42 | } |
---|
43 | |
---|
44 | void Linear::fit(const utility::vector& x, const utility::vector& y) |
---|
45 | { |
---|
46 | ap_.reset(); |
---|
47 | for (size_t i=0; i<x.size(); i++) |
---|
48 | ap_.add(x(i),y(i)); |
---|
49 | |
---|
50 | alpha_ = ap_.y_averager().mean(); |
---|
51 | beta_ = ap_.covariance() / ap_.x_averager().variance(); |
---|
52 | |
---|
53 | // calculating deviation between data and model |
---|
54 | mse_ = (ap_.y_averager().sum_xx_centered() - ap_.sum_xy_centered() * |
---|
55 | ap_.sum_xy_centered()/ap_.x_averager().sum_xx_centered() )/x.size(); |
---|
56 | r2_= 1-mse_/ap_.x_averager().variance(); |
---|
57 | alpha_var_ = mse_ / x.size(); |
---|
58 | beta_var_ = mse_ / ap_.x_averager().sum_xx_centered(); |
---|
59 | m_x_ = ap_.x_averager().mean(); |
---|
60 | } |
---|
61 | |
---|
62 | double Linear::predict(const double x) const |
---|
63 | { |
---|
64 | return alpha_ + beta_ * (x-m_x_); |
---|
65 | } |
---|
66 | |
---|
67 | double Linear::standard_error(const double x) const |
---|
68 | { |
---|
69 | return sqrt( alpha_var_+beta_var_*(x-m_x_)*(x-m_x_)); |
---|
70 | } |
---|
71 | |
---|
72 | }}} // of namespaces regression, yat, and theplu |
---|