#! /usr/bin/env python3 # def ford_lstsq ( ): #*****************************************************************************80 # ## ford_lstsq uses a least squares solver to model Ford data. # # Discussion: # # Least squares solver for optimal (b,m) to fit (x,y) data # y = b + m*x # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 09 October 2019 # # Author: # # John Burkardt # import numpy as np from ford_data import ford_data print ( '' ) print ( 'ford_lstsq:' ) print ( ' Given mileage x and price y for used Fords,' ) print ( ' seek (m,b) so that y=b+mx approximates the data.' ) print ( ' Use least squares solver to estimate best b and m.' ) # # Get the (normalized) Ford data. # x, y = ford_data ( ) n = len ( x ) # # Create the matrix A: # A = np.zeros ( [ n, 2 ] ) A[:,0] = 1; A[:,1] = x; # # Call least squares solver for rectangular linear system. # Four output quantities are returned, but we are only # interested in the first one, so we put underscores to # ignore the last three. # bm, _, _, _ = np.linalg.lstsq ( A, y, rcond = None ) print ( '' ) print ( ' Estimating model parameters:' ) print ( ' x = normalized mileage' ) print ( ' y = normalized price' ) print ( ' Seek relationship y = b + m * x' ) print ( ' b = %g' % ( bm[0] ) ) print ( ' m = %g' % ( bm[1] ) ) e = np.sum ( ( y - bm[0] - bm[1] * x )**2 ) print ( ' Sum-of-squares error is %g' % ( e ) ) # # Terminate. # print ( '' ) print ( 'ford_lstsq:' ) print ( ' Normal end of execution.' ) return if ( __name__ == '__main__' ): ford_lstsq ( )