gonum.org/v1/gonum@v0.14.0/stat/stat_example_test.go (about)

     1  // Copyright ©2018 The Gonum Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package stat_test
     6  
     7  import (
     8  	"fmt"
     9  
    10  	"golang.org/x/exp/rand"
    11  
    12  	"gonum.org/v1/gonum/stat"
    13  )
    14  
    15  func ExampleLinearRegression() {
    16  	var (
    17  		xs      = make([]float64, 100)
    18  		ys      = make([]float64, 100)
    19  		weights []float64
    20  	)
    21  
    22  	line := func(x float64) float64 {
    23  		return 1 + 3*x
    24  	}
    25  
    26  	for i := range xs {
    27  		xs[i] = float64(i)
    28  		ys[i] = line(xs[i]) + 0.1*rand.NormFloat64()
    29  	}
    30  
    31  	// Do not force the regression line to pass through the origin.
    32  	origin := false
    33  
    34  	alpha, beta := stat.LinearRegression(xs, ys, weights, origin)
    35  	r2 := stat.RSquared(xs, ys, weights, alpha, beta)
    36  
    37  	fmt.Printf("Estimated offset is: %.6f\n", alpha)
    38  	fmt.Printf("Estimated slope is:  %.6f\n", beta)
    39  	fmt.Printf("R^2: %.6f\n", r2)
    40  
    41  	// Output:
    42  	// Estimated offset is: 0.988572
    43  	// Estimated slope is:  3.000154
    44  	// R^2: 0.999999
    45  }