2 * linear least squares model
4 * Copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 * linear least squares model
31 #undef NDEBUG // allways check asserts, the speed effect is far too small to disable them
35 #define av_log(a,b,...) printf(__VA_ARGS__)
38 void av_init_lls(LLSModel *m, int indep_count){
39 memset(m, 0, sizeof(LLSModel));
41 m->indep_count= indep_count;
44 void av_update_lls(LLSModel *m, double *var, double decay){
47 for(i=0; i<=m->indep_count; i++){
48 for(j=i; j<=m->indep_count; j++){
49 m->covariance[i][j] *= decay;
50 m->covariance[i][j] += var[i]*var[j];
55 double av_solve_lls(LLSModel *m, double threshold){
57 double (*factor)[MAX_VARS+1]= &m->covariance[1][0];
58 double (*covar )[MAX_VARS+1]= &m->covariance[1][1];
59 double *covar_y = m->covariance[0];
61 int count= m->indep_count;
63 for(i=0; i<count; i++){
64 for(j=i; j<count; j++){
65 double sum= covar[i][j];
68 sum -= factor[i][k]*factor[j][k];
73 factor[i][i]= sqrt(sum);
75 factor[j][i]= sum / factor[i][i];
78 for(i=0; i<count; i++){
79 double sum= covar_y[i+1];
81 sum -= factor[i][k]*m->coeff[k];
82 m->coeff[i]= sum / factor[i][i];
85 for(i=count-1; i>=0; i--){
86 double sum= m->coeff[i];
87 for(k=i+1; k<count; k++)
88 sum -= factor[k][i]*m->coeff[k];
89 m->coeff[i]= sum / factor[i][i];
93 for(i=0; i<count; i++){
94 double sum= m->coeff[i]*covar[i][i] - 2*covar_y[i+1];
96 sum += 2*m->coeff[j]*covar[j][i];
97 variance += m->coeff[i]*sum;
102 double av_evaluate_lls(LLSModel *m, double *param){
106 for(i=0; i<m->indep_count; i++)
107 out+= param[i]*m->coeff[i];
123 for(i=0; i<100; i++){
125 double eval, variance;
126 var[1] = rand() / (double)RAND_MAX;
127 var[2] = rand() / (double)RAND_MAX;
128 var[3] = rand() / (double)RAND_MAX;
130 var[2]= var[1] + var[3];
132 var[0] = var[1] + var[2] + var[3] + var[1]*var[2]/100;
134 eval= av_evaluate_lls(&m, var+1);
135 av_update_lls(&m, var, 0.99);
136 variance= av_solve_lls(&m, 0.001);
137 av_log(NULL, AV_LOG_DEBUG, "real:%f pred:%f var:%f coeffs:%f %f %f\n",
138 var[0], eval, sqrt(variance / (i+1)),
139 m.coeff[0], m.coeff[1], m.coeff[2]);