#! /usr/bin/env python3 # def homes ( ): #*****************************************************************************80 # ## homes() makes a linear model of home selling prices. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 21 August 2019 # # Author: # # John Burkardt # import matplotlib.pyplot as plt import numpy as np data = np.loadtxt ( 'homes_data.txt' ) # # Extract data items. # ask = data[:,0] sel = data[:,1] liv = data[:,2] rms = data[:,3] bed = data[:,4] bat = data[:,5] age = data[:,6] lot = data[:,7] tax = data[:,8] # # Count data items. # n = len ( ask ) print ( ' Number of listings is ', n ) # # Create matrix A = [1,liv,rms,bed,bat,age,lot,tax]. # A = np.zeros ( [ n, 8 ] ) A[:,0] = np.ones ( n ) A[:,1] = liv A[:,2] = rms A[:,3] = bed A[:,4] = bat A[:,5] = age A[:,6] = lot A[:,7] = tax cask, _, _, _ = np.linalg.lstsq ( A, ask, rcond = None ) # # Use A and c to evaluate the linear model for the bill. # ask_predict = np.dot ( A, cask ) # # Print the formula # print ( 'predicted asking price = ' ) print ( '%g' % ( cask[0] ) ) print ( '+ %g * living space' % ( cask[1] ) ) print ( '+ %g * number of rooms' % ( cask[2] ) ) print ( '+ %g * number of bedrooms' % ( cask[3] ) ) print ( '+ %g * number of bathrooms' % ( cask[4] ) ) print ( '+ %g * age in years' % ( cask[5] ) ) print ( '+ %g * lot size in acres' % ( cask[6] ) ) print ( '+ %g * annual taxes in dollars.' % ( cask[7] ) ) # # Plot the actual and predicted asking prices. # askmin = min ( ask ) askmax = max ( ask ) mm = np.array ( [ askmin, askmax ] ) plt.plot ( mm, mm, 'r-', linewidth = 3 ) plt.plot ( ask, ask_predict, 'bo', markersize = 10 ) plt.grid ( True ) plt.xlabel ( 'Actual asking price' ) plt.ylabel ( 'Predicted asking price' ) plt.title ( 'Linear model of asking price for a house.' ) filename = 'homes.png' plt.savefig ( filename ) print ( ' Graphics saved as "', filename, '"' ) plt.show ( ) # # Compute a selling price for a new listing. # data2 = np.loadtxt ( 'homes_test.txt' ) # # Extract new data items. # ask2 = data2[:,0] sel2 = data2[:,1] liv2 = data2[:,2] rms2 = data2[:,3] bed2 = data2[:,4] bat2 = data2[:,5] age2 = data2[:,6] lot2 = data2[:,7] tax2 = data2[:,8] # # If only one new listing, force it to "look like" a vector. # ask2 = np.atleast_1d ( ask2 ) n2 = len ( ask2 ) print ( ' Number of new listings is ', n2 ) A2 = np.zeros ( [ n2, 8 ] ) A2[:,0] = np.ones ( n2 ) A2[:,1] = liv2 A2[:,2] = rms2 A2[:,3] = bed2 A2[:,4] = bat2 A2[:,5] = age2 A2[:,6] = lot2 A2[:,7] = tax2 # # Evaluate the linear model. # ask2_predict = np.dot ( A2, cask ) print ( '' ) print ( ' Realtor Model' ) print ( '' ) for i in range ( 0, n2 ): print ( ' %g %g' % ( ask2[i], ask2_predict[i] ) ) return if ( __name__ == "__main__" ): homes ( )