Full text
Generalized Additive Model Implementation for Germany Real Estate Market Model, API, UI Development Berk Münger Internship Report presented as the partial requirement fo r obtaining a Master's degree in Data Science and Advanced Analytics
ii NOVAInformationManagementSchool InstitutoSuperiordeEstatísticaeGestãodeInformação UniversidadeNovadeLisboa Generalized Additive Model Implementation for Germany Real Estate Market Model, API, UI Development by BerkMÜNGER Internship Report presented as the partial requirement for obtaining a Master's degree in Data Science and Advanced Analytics Advisor: Bruno Miguel Pinto Damásio External Supervisor: Stephan Zhechev November 2020
iii ABSTRACT Hedonic pricing approach one of the most accepted methodologies for the real estate price assessment by delivering attribute-based value. It emerges from the value changing regarding object attributes conditions. In real estate market, these changes can be property renovation, material, and construction depreciation, or even expanding the plot area. The scope of the internship report is to be explained the development first prototype General Additive Model of predicting House square meter price basis on Hedonic pricing theory for a certain region of Germany. In addition to the model development, bringing it into live via Rest API and User Interface is explained in this report. Data Science Service GMBH is the owner of the project and specialized in real estate property appraisal that is derived from statistical learning models, currently only at Austria. The outcome of this project enables us to get into Germany Real Estate Market as well. The necessary data has been brought by German Market Partner, Forschung und Beratung für Wohnen, Immobilien und Umwelt GmbH (F+B), however Data Science Service GMBH (DSS) is responsible for delivering the model product from beginning to end. R Programming Drake package is used for parallel computation and to be generated maintainable adaptive data pipeline. Parameter selection based on information criteria has been done for each model in every kind of real estate property. Lastly, the statistical model is delivered by rest API to UI (Shiny Application), both are developed with R programming language. KEYWORDS General Additive Model (GAM); Hedonic pricing theory; Real estate property appraisal; mgcv.
iv INDEX 1. Introduction .................................................................................................................. 1 2. Literature review .......................................................................................................... 4 2.1. Hedonic Price Method (HPM) ............................................................................... 4 2.2. Generalized Additive Model .................................................................................. 5 2.2.1. General Additive Model (GAM) ...................................................................... 5 2.2.2. Smoothers (Splines) ........................................................................................ 6 2.2.3. Real Estate Market Covariates ....................................................................... 8 2.2.4. Spatial Heterogeneity in GAM ........................................................................ 8 3. GAM Model IMPLEMENTATION ................................................................................... 9 3.1. Data Preparation ................................................................................................... 9 3.2. Data Transformation ........................................................................................... 10 3.2.1. Geocoding ..................................................................................................... 10 3.2.2. Migration ...................................................................................................... 10 3.2.3. Data Transformation .................................................................................... 10 3.2.4. Granular Spatial Data Merging ..................................................................... 12 3.3. Data Imputation .................................................................................................. 12 3.3.1. Out-of-bag (OOB) score ................................................................................ 12 3.3.2. Tuning Parameters for random forest ......................................................... 13 3.4. Model ................................................................................................................... 14 3.4.1. Model Validation .......................................................................................... 15 3.4.2. Price Trend for Model .................................................................................. 19 3.4.3. Model Preparation for API ........................................................................... 19 4. MODEL DEPLOYMENT ................................................................................................ 20 4.1. Data Pipeline........................................................................................................ 20 4.2. Rest Api ................................................................................................................ 21 4.3. User Interface ...................................................................................................... 21 5. Results and discussion ................................................................................................ 22 6. Conclusions ................................................................................................................. 24 7. Limitations and recommendations for future works ................................................. 25 8. Bibliography ................................................................................................................ 26 9. Appendix ..................................................................................................................... 29 9.1. MGCV Package Usability ...................................................................................... 29 9.2. Offset Inputs ........................................................................................................ 29
v 9.3. Data Imputation R Code ...................................................................................... 30 9.4. Fitted Model Data Exploration ............................................................................ 31 9.4.1. Correlation Table .......................................................................................... 31 9.4.2. Density Functions ......................................................................................... 31 9.4.3. Distribution for Furnshing ............................................................................ 32 9.5. Base Formel Preparation ..................................................................................... 32 9.6. XGBOOST – Residual Model ................................................................................ 33 9.7. Selected Model Output ....................................................................................... 33 9.7.1. GAM Model (GCV / TP) ................................................................................. 33 9.7.2. XGBoost Model ( GCV / TP ) ......................................................................... 34 9.8. Descriptive Statistics ............................................................................................ 35 9.9. Model Validation Tests ........................................................................................ 36 9.9.1. Moran’s I Result ............................................................................................ 36 9.9.2. Moran’s Functions ........................................................................................ 36 9.9.3. Bartlett Test .................................................................................................. 36 9.9.4. Jarque Bera Test ........................................................................................... 37
vi LIST OF FIGURES Figure 1-1: GAM Model Variable Effect in Hedonic Pricing ....................................................... 1 Figure 2-1 Smoothing Parameter Effect Comparison ............................................................... 6 Figure 3-1: Log Transformation for House Area ...................................................................... 11 Figure 3-2: Log Transformation for Plot Area .......................................................................... 11 Figure 3-3: Variable Importance at Imputing of Age ............................................................... 13 Figure 3-4: REML / TP Partial Effect of Variables ..................................................................... 13 Figure 3-5: Response vs Fitted Values for GAM ....................................................................... 16 Figure 3-6: Residual Distribution .............................................................................................. 17 Figure 3-7: Residual Fitted Value Comprasion ......................................................................... 18 Figure 3-8: Market price development .................................................................................... 19 Figure 4-1: Drake Data Pipeline Diagram ................................................................................. 20 Figure 4-2: API UI Interaction ................................................................................................... 21 Figure 5-1: Test Dataset Error Distribution .............................................................................. 22 Figure 5-2: Test Dataset Price Accuracy Percentage ................................................................ 23 Figure 6-1: Screenshot of Immazing Germany Quick Product ................................................. 24 Figure 9-1: Correlation Among Variables ................................................................................. 31 Figure 9-2: Variables Correlation with log m² Price ................................................................. 31 Figure 9-3: log m² Price – log Area Density Distribution .......................................................... 31 Figure 9-4: Furnishing Effect on log m² Price ........................................................................... 32
vii LIST OF TABLES Table 1-1: Observations with Granular Levels ........................................................................... 2 Table 2-1: Most well-known HPM Literature in Real Estate Market ......................................... 4 Table 2-2: Limitation of GLM and Linear Regression ................................................................. 5 Table 2-3: GAM – GZLM Models comparision ........................................................................... 5 Table 3-1: Model Data Inputs Overview .................................................................................... 9 Table 3-2: Data Transformations ............................................................................................. 11 Table 3-3: Spatial Data Variables ............................................................................................. 11 Table 3-4: Grid Research Result Top 10 Lowest Error .............................................................. 12 Table 3-5: Mode Fitting Result ................................................................................................. 13 Table 5-1: GAM Model Result .................................................................................................. 22 Table 9-1: Model Offset Values ................................................................................................ 29 Table 9-2: Descriptive Statistics Continuous Variables ............................................................ 35 Table 9-3: Descriptive Statistics Categorical Variables ............................................................ 35
viii LIST OF ABBREVIATIONS AND ACRONYMS DSS Data Science Service GMBH GAM General Additive Model GLM General Linear Model GZLM Generalized Linear Model GCV Generalized Cross-Validation AIC Akaike Information Criterion HPM Hedonic Price Methodology OOB Out of Bag Error EFH House Property ETW Flat Property PLZ Postal Code W Wiggleness re Random Effect PIRLS Poisson Iteratively Reweighted Least Squares cr Cubic Regression Splines TPRS Thin Plate Regression Splines REML Restricted maximum likelihood
1 1. INTRODUCTION Statistical value assessment for real estate properties is not only crucial for the governments and the authorities but also vastly important for Banks and Insurance Companies. Since the subprime mortgage crisis happened in 2007, especially financial risk department of the banks whose offer individual housing loan strictly rely on the statistical analysis outcomes and its derivative results. Even though the monthly published official real estate price index allows to be tracked general market trend for each country, it is not comprehensive enough in assessing individual property value except being an input for more extended analysis. This analysis can be conducted with real estate property characteristics such as location, construction year, floor, area size, room number even floor material. Therefore, in the real estate market, the characteristics prices approach highly preferable because of its simplicity as well as the fact that the property most likely to be revised on time. The hedonic price methodology (HPM), that most well know and valid characteristics prices approach at the real estate market and it is presented with joint envelope function that includes all characteristics as variable, implicitly with their price effect for every single characteristic. Hedonic price methodology can be implemented through various algorithm however, black-box algorithms don’t guarantee the interpretability of model regarding character changes in first prototype development. The functional form model that also allows nonlinearities has broadly used Wallace (1996) or Malpezzi (2003). General Additive Model (GAM) offers nonlinear relation in functional from including covariates effects. Moreover, some variables are strictly known as positive (garage) or negative (age) effect for predicted value in any circumstances, hence the predicted value should be updated in the expected direction. GAM model can be adjusted also within that scope. Figure 1-1: GAM model variable effect in Hedonic Pricing Age: - 26 % Area: -3,1 % 35 55 90 15 0 24 0 2014-04 2014-10 2015-05 2015-11 2016-06 2016-01 2016-07 Trend: +3,8 % Location: - 1,1 %
8 ∑(𝑦𝑖−𝑓(𝑥𝑖))2 𝑛 𝑖=1 + λ∫(𝑠′′(𝑥))2𝑑𝑥 Fit observed data Penalty Term 2.2.3. Real Estate Market Covariates The floor area is the central property characteristic and a pronounced positive effect on the purchase price is expected. Malpezzi (2003) advises a logarithmic transformation considering multiplicative structures. Year of sale and year of construction reflects property depreciation over time and should therefore have a decreasing effect on flat prices. Nevertheless, a vintage effect, which has the opposite consequences, is possible (Can, 1998, pp. 61-86). Goodman and Thibodeau (2003, pp. 181-201) and Brunauer (2010) report non-linear age effects. The year of the time of sale can be regarded as the remaining unexplained temporal heterogeneity. It is a measure for the quality adjusted development of prices over time and is modeled as a numeric covariate. 2.2.4. Spatial Heterogeneity in GAM Fixed effects can be integrated by allowing the intercepts vary over space. Slope heterogeneity can be controlled through spatial interaction effects with explanatory covariates (Kestens, 200). heterogeneity using many fixed effects can result in insufficient observations within regions for parameter estimations which, due to the loss of degrees of freedom, decrease the prediction accuracy. Therefore, it is common practice to interact where only "one-variable-at-a-time" is considered (McMillen and Redfearn, 2010, pp. 713). Thus, a trade-off between both data fidelity and reduction of prediction accuracy is required which is partially solved by the random effects model (Goldstein, 2011). The simplest random effects model is the one-way intercept model, whereby intercepts vary spatially. Random effects can be approximated as a weighted average of the mean of the observations in the spatial units (corresponding to a dummy specification) and the overall mean of the whole country (Gelman & Hill, 2007). The weights are determined by the amount of information in each region. Random effects models can be generalized by two-way structures (e.g., random time effects) and by letting predictors interact with the random effects, allowing different intercepts and/or slopes within each region (Goldstein, 2011).
9 3. GAM MODEL IMPLEMENTATION The general additive model was conducted following steps: 1. Data Preparation 1.1. Data Cleaning and Outlier Treatment 1.2. Data Imputation with Random Forest 1.3. Data Transformation 2. Model Fitting 2.1. Generalized Linear Model 2.2. General Additive Model 2.2.1. Spline: Cubic Spline, Smoothing Parameter Selection: GCV and REML, Knots: 5 2.2.2. Spline: Thin Plate Spline, Smoothing Parameter Selection: GCV and REML, Knots: Each Observation – PCA method: eigen decomposition. 2.3. Ensemble Learning: Model Residual – XGBoost + General Additive Model 3. Model Validation 3.1. DATA PREPARATION Table 3-1: Model Data Inputs Overview Data has been cleaned from the variables that are not planned to be used in model development such as sauna, pool. Unbalanced amount of inputs most likely was reason of cleaning. (Appendix – 9.3. Deleted Variables) General Additive Model is highly sensitive of outliers. Therefore, strict outlier treatment has been conducted with heuristic approach such as houses older than 150 year is changed with 150. Time inputs corresponds to advertised time of property. Older than 2014 advertisement deleted from raw data. Outliers are treated into same function with data transformation. (Appendix – 9.4. Data Preparation Function) Offset Condition is prepared for adding to the GAM model that enables the predicted value differentiation even though the model doesn’t includes that variable as independent variable such as “swimming pool”. (Appendix – 9.2. Offset Values for House) PREPARED DATA Binary stell balc rh dhh wintergarten garten loggia furnishing gar cell villa renovation Continuous log transformed Time Location age ln_area year_fac KGS05a Rating ln_plot quarter PLZ1 efh_bp offset_cond
10 Data describing the neighborhood or location is accounted for on the most granular level available, in a possibly nonlinear functional form as splines – non parametric functions 3.2. DATA TRANSFORMATION The model pipeline is run since new data has been presented for model improvement. Pipeline steps has instructed below respectively. 3.2.1. Geocoding The raw data obtained from German Partner (F+B) is not including longitude-latitude information of observations. Therefore, the dataset is sent to Wigeogis (GIS Data Solution Provider) in order to obtain lon, lat from property address information. Generated lon, lat information is merged back to raw data. adr_qua_short column is categorical variable that defines quality of address description into address input and it enables us to classify which observations are well geocoded. 3.2.2. Migration The raw data variable names are adapted into master data schema which is designed by DSS for the purpose of variable name unification also considering Austria Data. Therefore, the variables are renamed and transformed according to the model needs. Variable types are aligned with expected variable types. In addition to variable renaming, variable values also refactored with set of rules such as date Format, upper lower Case, treatment of NA, NULL, “” values. 3.2.3. Data Transformation Even though the dataset is refined to populate a database, the input variables have not been treated enough to construct GAM Model yet. Data anomalies are detected and set to fixed values. Outlier treatments are made with simple calculations using empirical thresholds. Descriptions Value Transformation model_obj_type String Observations are classified among Flat (etw), Rent Flat (etw_miete), House (efh) and Rent House (efh_miete). This variable enables to determine constructing model type. rh Binary ( 0 / 1 ) House Type: Townhouse. One Type of House and determined considering "haustyp" string input. Looking inputs: "REIHENECK","REIHENEND","REIHENHAUS","REIHENMITTEL" dhh Binary ( 0 / 1 ) House Type: Semi Detach House. One Type of House and determined considering "haustyp" string input. Inputs: "DOPPELHAUSHAELFTE", "MEHRFAMILIENHAUS", "ZWEIFAMILIENHAUS", "APARTMENTHAUS", villa Binary ( 0 / 1 ) House Type: Villa. Inputs: "DOPPELHAUSHAELFTE", "MEHRFAMILIENHAUS", "ZWEIFAMILIENHAUS", "APARTMENTHAUS"
11 letztemodernisier ung (renavation year) numeric letztemodernisierung < 1990 OR letztemodernisierung < baujahr (construction year) + 5 set NA or RENAVATION YEAR Factor of Year (factor) Factor real estate conveyed date will be used as categorical variable into GAM Model cond3_gut ( Furnishing Condition) Factor (0,1) Binary Categorical Input for Model cond1_schlecht ( Furnshing Condition ) Factor (0,1) Binary Categorical Input for Model saniert ( renovated ) Factor (0,1) Binary Categorical Input for Model as depends on hauszustand (house condition) input Wohnflache House Area ln_area Age Current Year – Construction Year ln_age Grundstuckflache Plot area ln_plot Table 3-2: Data Transformations Below Figures show the log transformations: Figure 3-1: Log Transformation for House Area Figure 3-2: Log Transformation for Plot Area
12 3.2.4. Granular Spatial Data Merging Each observation at current dataset only includes coordinates (longitude and latitude) and PLZ (postal code) information. In this step, this dataset will be enriched with Germany State codes, name, real estate property index information basis on postal code. (efh_bp) For observations that doesn’t have coordinate information however valid postal code data, Postal Code Centroids have assigned as coordinates. Binary value for variable exact_geocode is set to “0”. Implicit cleaning for observations that do not have valid postal code is made. Duplicated data is deleted from dataset regarding square meter, year, coordinates, sales price, advertised year. Added variables are: Variable Type Description exact_geocode Binary value Indicates the property is whether coordinated exactly or not Rating Discrete value property scoring point generated data by German Business Partner KGS02a Spatial Factor A certain Region belongs to a state consists of some Postal Code efh_bp Continuous value Price index for per m² PLZ Spatial Factor Postal Code Lat_plz / lon_plz Spatial Factor Coordinates of Centre of PLZ Table 3-3: Spatial Data Variables 3.3. DATA IMPUTATION Data Imputation for the variables “age” and “ln_plot” highly important before fitting into the model. Therefore, these two variables have taken care of with random forest method due to having highly computation power through ranger R packages. Out-of-bag error (OOB) Error estimate has been preferred in tuning of parameters. The study of error estimates in ), gives empirical evidence to show that the out-of-bag estimate is as accurate as using a test set of the same size as the training set. Therefore, using the out-of-bag error estimate removes the need for a set aside test set. The imputation is done for every subregion of all data. Below example only belongs to 1200 real estate property that is grouped of certain postal codes for age variable. 3.3.1. Out-of-bag (OOB) score Each individual tree of a random forest uses a sample of the rows of the dataset which means that some of the rows did not get used for training. We can take advantage of this fact and pass those unused rows through the first tree and treat it as a validation set. For the second tree, we could pass through the rows that were not used for the second tree, and so on. Similarly, we can perform the same procedure for all the trees of the Random Forest. Effectively, we now have a different validation set for each tree. To calculate our prediction, we would average all the trees where that row is not used for training.
13 3.3.2. Tuning Parameters for random forest 𝑚𝑡𝑟𝑦 : The hyperparameter that controls the split-variable randomization feature of random forests. It helps to balance low tree correlation with reasonable predictive strength. In default it is preferred to be selected as equals to 𝑓𝑒𝑎𝑡𝑢𝑟𝑒 𝑞𝑢𝑎𝑛𝑡𝑖𝑡𝑦 3 that indicates 7. 𝑁𝑢𝑚𝑏𝑒𝑟 𝑜𝑓 𝑡𝑟𝑒𝑒𝑠 : the number of trees needs to be sufficiently large to stabilize the error rate. A good rule of thumb is to start with 10 times the number of features; however, as you adjust other hyperparameters such as 𝑚𝑡𝑟𝑦 and node size, more or fewer trees may be required. 220 number of trees is set in default. Grid search across several hyperparameters is done for finding optimum number of trees and randomized feature between 1-20 and 50-200 respectively. Feature importance basis on the average total reduction of the loss function for a given feature across all trees for imputing age. Figure 3-3: Variable Importance imputing of age mtry num.trees OOB_RMSE perc_gain 11 450 2.390.263 1.475.819 7 250 2.390.441 1.468.479 12 350 2.390.629 1.460.753 12 400 2.393.701 1.334.134 9 300 2.394.126 1.316.590 8 250 2.394.456 1.303.014 9 450 2.394.805 1.288.611 10 500 2.395.058 1.278.182 12 250 2.395.525 1.258.952 9 200 2.397.287 1.186.299 Table 3-4: Grid Research Result Top 10 Lowest Error
14 3.4. MODEL The data that will be fit into model is to be explored at Appendix 9.4 The multiple model is constructed regarding two different spline selection method and two different smoothing parameter selection methodology in addition to one simple GLM model. Following procedure is followed in fitting GAM Model: 1) The variables and corresponding signs are introduced. For instance, adding a balcony to an apartment should increase the price rather than decreasing it. The variables that cannot be known also specified. (Appendix 9.5) 2) Three types of smoothers are used in selecting of splines weighting: thin plate regression splines (TPRS), cubic regression splines (CRS), and random effects. 𝑙𝑛𝑝_𝑞𝑚~ 𝑠(𝐾𝐺𝑆05𝑎 ,𝑏𝑠=′𝑟𝑒′)+𝑠(𝑃𝐿𝑍1,𝑏𝑠=′𝑟𝑒′,𝑏𝑦=𝑏𝑦_𝑝𝑙𝑧) + 𝑠(𝑙𝑛𝑎𝑟𝑒𝑎)+ 𝑠(𝑙𝑛𝑝𝑙𝑜𝑡)+ 𝑠(𝑎𝑔𝑒)+ (𝑞𝑢𝑎𝑟𝑡𝑒𝑟,𝑏𝑠=′𝑟𝑒′) a. 𝑠(𝑙𝑛𝑎𝑟𝑒𝑎)+ 𝑠(𝑙𝑛𝑝𝑙𝑜𝑡)+ 𝑠(𝑎𝑔𝑒) These are splined with two different method. CRS and TPRS spline types are used for these three smoothing functions. b. 𝑠(𝐾𝐺𝑆05𝑎 ,𝑏𝑠=′𝑟𝑒′) Random effect is to most simple way to obtain group-level splines. This is useful if different groups differ substantially in how wiggly they are. Therefore, random effect spline methodology is fixed for census track level data. Besides each real estate advertised time is considered with random effect. 3) Two different smoothing parameter selection methodology is conducted. a. Minimized generalized cross-validation (GCV) score: This method is selected as a argument of GAM function sourced by mgcv R package. The below procedure is followed at fitting data into model: 1. Leave out observation i 2. Estimate a smoothing curve using the n-1 remaining observations 3. Predict the value at omitted point 𝑋𝑖 4. Compare predicted value at 𝑋𝑖 with real value 𝑌𝑖 5. The difference between the original and predicted value at 𝑋𝑖 is given by 𝑌𝑖−𝑓λ−𝑖(𝑋𝑖) This process is repeated for each observation 6. Adding up all squared residuals gives the cross-validation error 𝐶𝑉[λ]=1 𝑛∑(𝑌𝑖−𝑓λ−𝑖(𝑋𝑖))2 𝑛 𝑖=1 7. The cross-validation error is calculated for various values of the smoothing parameter. The value of parameter that gives lowest value for CV is considered the closest the optimal amount of smoothing.
15 b. Restricted Maximum Likelihood (REML) Since GAM has a Bayesian interpretation it can be treated like a standard mixed model by separating out the fixed effects and estimating the smoothing parameters as variance parameters. The variance of the coefficients depend on p, which in turn depends on λ = λ1, . . ., λp.) The restricted likelihood function, given the vector of smoothing parameters, λ, is obtained by integrating out beta from the joint density of the data and the coefficients. (Wood, 2004). 𝑙𝑟(β ,λ)= ∫𝑓(𝑦\β)𝑓(β)𝑑𝛽 The restricted likelihood function depends on λ and the estimates β (through the penalty), but not the random parameters β. Thus, it can be used this function to derive trial vectors for λ for a nested PIRLS iteration: 1. Given a trial vector λ, estimate β using PIRLS. 2. Update λ by maximizing the restricted log likelihood. 3. Repeat steps 1 and 2 until convergence. 4) Ensemble Learning - XGBoosting In boosting, the trees are built sequentially such that each subsequent tree aims to reduce the errors of the previous tree. Each tree learns from its predecessors and updates the residual errors. Hence, the tree that grows next in the sequence will learn from an updated version of the residuals. (Appendix 9.6) 1. An initial model F0 is defined to predict the target variable y. This model will be associated with a residual (y – F0) 2. A new model h1 is fit to the residuals from the previous step 3. Now, F0 and h1 are combined to give F1, the boosted version of F0. The mean squared error from F1 will be lower than that from F0 3.4.1. Model Validation Splines Effective Degree of Freedom (edf) GCV / TP REML / TP GCV / CR REML / CR s(KGS05a) 39.883 44.979 36.897 44.976 s(PLZ1):by_plz 806.171 750.318 813.616 750.302 s(ln_area) 7.661 7.841 8.743 8.404 s(ln_plot) 8.716 8.508 7.246 7.857 s(age) 7.877 7.879 8.541 8.720 s(quarter) 17.704 17.703 17.690 17.703 Table 3-5: Mode fitting result
16 edf : corresponds to smoothing parameter (𝜆), in other words estimated wiggleness. 𝐸𝑑𝑓 > 8 means highly non-linear curve, edf = 1 means straight line. The below plots shows the change of the spline functions with regards to variable. Generally speaking, the more age, the function s(age) decrease, The decrease is less pronounced when it increases from 100 to 130. Shade area represents the confidence interval. Figure 3-4: REML / TP Partial effect of variables Gam.check function in mgcv package enables to make validation easily for GAM models with regards to graphical steps. Estimated value and Response value comparison is good indicator when assessing the mode performance in general aspect. Figure 3-5: Response vs Fitted Values for GAM
17 3.4.1.1. Normality Check Figure 3-6: Residual Distribution . Jarque-Bera test is conducted in order to check the distribution of residual is whether normal or not. It is a goodness-of-fit test that simply aims to match the skewness and kurtosis of data with normal distribution. 𝐻0 : 𝑇ℎ𝑒 𝑑𝑎𝑡𝑎𝑠𝑒𝑡 𝑖𝑠 𝑓𝑟𝑜𝑚 𝑎 𝑛𝑜𝑟𝑚𝑎𝑙 𝑑𝑖𝑠𝑡𝑟𝑖𝑏𝑢𝑡𝑖𝑜𝑛 𝐻1 : 𝑂𝑡ℎ𝑒𝑟𝑤𝑖𝑠𝑒 Ontained highly low value indicates that null hypothesis is rejected. The residual is not normally distributed. 3.4.1.2. Homogeneity Check Standardized Residual should spread randomly everywhere at Residual and Fitted Value Graph. Bartlett's test is used to test this assumption that variances are equal across data through groups data input. The data is separated to 4 groups through K means clustering and residual is set as input for Bartlett’s test. 𝐻0 : 𝑉𝑎𝑟𝑖𝑎𝑛𝑐𝑒 ( 𝜎2 ) 𝑖𝑠 𝑒𝑞𝑢𝑎𝑙 𝑎𝑐𝑟𝑜𝑠𝑠 𝑎𝑙𝑙 𝑔𝑟𝑜𝑢𝑝𝑠 𝐻1 :𝑉𝑎𝑟𝑖𝑎𝑛𝑐𝑒 𝑖𝑠 𝑛𝑜𝑡 𝑒𝑞𝑢𝑎𝑙 𝑎𝑐𝑟𝑜𝑠𝑠 𝑎𝑙𝑙 𝑔𝑟𝑜𝑢𝑝𝑠 The obtained P-Value extremely lower than significance level (0.05), so the null hypothesis is rejected. Even though below graph indicates that there is no clear correlation between predicted price and residual, residual distribution depends on object characteristics such as age, furnishing, ln_plot etc.
24 6. CONCLUSIONS First prototype of non-parametric statistical model that references the hedonic price theory for Data Science Service GMBH has been developed and bring it into production and became ready to use through API for German Market. The preferred statistical model was the GAM Model that DSS is specialized at Austria Real estate market. Even though GAM has advantage of capturing the shape of relationship without prejudging the issue by choosing a parametric form, however, one of the main disadvantages is very sensitive with gaps in the data and outlier. Therefore, strict outlier treatment was done in model preparation step such as real estate advertised year limited with 2014. Hierarchal spatial data such as postal code, state was treated with 2 level of census track random effect. Time input also is also categorized as quarter and included GAM model with random effect. Highly correlated non-linear continuous variables are regressed with smoothing functions. It makes possible to increase degree of freedom without losing interpretability of model. (Appendix 9.4.1.) GAM model was gained sensitivity with offset values. These empirical values made the model sensitive also different independent variables. Data was trained with 4 different GAM model and GLM model. GAM models were diversified regarding smoothing function (spline) selection methodology and smoothing parameter selection methodology. The most well-known spline selection methods, thin plate and cubic regression spline selection methods; commonly used smoothing parameter selection methods, generalized cross validation (GCV) and maximum likelihood (REML) are preferred. The results that was obtained from 4 different model proved that even if spline complexity increased, the penalized maximum likelihood didn’t allow overfitting whereas complexity decreased low smoothing parameter didn’t allow underfitting. Another conclusion was the different method selection was not impactful to increase fitting. GAM Model is ensembled with gradient boosting framework. Train dataset residuals are fitted with XGboost and MSE decreased 15% for test dataset. The first version model was run through API services and is brought into live! Figure 6-1: Screenshot of Immazing Germany Quick Product
25 7. LIMITATIONS AND RECOMMENDATIONS FOR FUTURE WORKS The project aim was to make it live a GAM model for Germany Market. Empirical data preparation that basis on concrete market experience in Austria enables to raise a GAM model for Germany. However, Model is groomed intensively for outliers. It is known that it increases model fitting performance, nonetheless it causes to return unsatisfied predicted result for certain real estate such as the house located next to lake. Even the statistical model is currently accessible for user, still not ready for promoting to our prospect customers. Model Validation results shows that the raw data should be extensively analyzed and cleansed. Obtained residuals with thin GAM model (thin plate regression spline, generalized cross validation parameter selection method) doesn’t meet any GZLM and GAM assumption. The amount of model, more than 2000, in case of only using one census track level, allocates 60 GB memory on server. It is not only made impossible to allow to user run one model in parallel way also limits the model improvement process in terms of usage of development server at the same time. In this study 2 census track level is used (KG05 and PLZ1) to prevent model from data losing. Therefore, reducing amount of model also by randomizing effect of region will make the model more usable and easier to improve. Moreover, model studies will be more impactful for all Germany. Macro Statistical / Environmental Variables are not considered into model yet such as distance to metro station, air quality, to name a few. These variables show great impact on Austria General Additive Model. Data losing due to not well geocoded will cause to not to be selected most convenient property for comparison-based method. Comparison Based method, finding price multiple for the properties based on some feature of the property which derives the property’s value. It involves dividing the property value by say its covered area, number of apartments. Therefore, synthetic geocoded should be imputed by considering similar objects with regards to their price at same postal code. Even though GAM allows us to deliver crystal box model, black box algorithms should be run at least in performance assessment. Beyond that, satellite image decomposition for learning or interior picture can be used for model learning.
26 8. BIBLIOGRAPHY Austria Real Estate Price Index. Retrieved from https://www.oenb.at/isaweb/report.do?lang=EN&report=6.6 Anglin, P., M., & Gencay R. (1996). Semiparametric Estimation of a Hedonic Price Function, Journal of Applied Econometrics, Vol. 11, No. 6, 633-648. Retrieved from https://onlinelibrary.wiley.com/doi/epdf/10.1002/%28SICI%291099- 1255%28199611%2911%3A6%3C633%3A%3AAID-JAE414%3E3.0.CO%3B2-T Can, A. (1998). GIS and spatial analysis of housing and mortgage markets. Journal of Housing Research, 61-86. Clapp, J., M. (2004). A Semiparametric Method for Estimating Local House Price Indices, Real Estate Economics 32(1), 127-160. Ekeland, I. (2004). Identification and Estimation of Hedonic Models, 2004, Journal of Political Economy 112(S1), 60. Retrieved from https://discovery.ucl.ac.uk/id/eprint/12718/ Follain, R. & Jimenez, E. (1985). Estimating the demand for housing characteristics, Volume 15, Issue 1, February, 77-107. De Boor (1978). A Practical Guide to Spline January Mathematics of Computation Volume 27, 149. Des Rosiers, F., Lagana, A., Theriault, M. & Beaudoin, M. (1996). Shopping centres and house values: An empirical investigation, Journal of Property Valuation & Investment, vol. 14, 41-62. Duchon (1977). Thin Plate Splines. Retrieved from http://web.mit.edu/~r/current/arch/i386_linux26/lib/R/library/mgcv/html/smooth.construct. ds.smooth.spec.html Gelman, A. & Hill, J. (2007). Data analysis using regression and multilevel/hierarchical models. Cambridge: Cambridge University Press. Goodman, A. & Thibodeau, T. (2003). Housing market segmentation and hedonic prediction accuracy, Journal of Housing Economics, 12, 181-201. Goodman, A. (1998). Andrew Court and the Invention of Hedonic Price Analysis, 291-298. Goldstein, H. (2011). Multilevel statistical models. Chichester, Wiley. Griliches Z. (1961). Hedonic Price Indexes for Automobiles: An Econometric of Quality Change. Retrieved from https://www.nber.org/system/files/chapters/c6492/c6492.pdf Hastie, T.J. & Tibshirani, R. (1990). Generalized Additive Models. Hastie,T.J. & Tibshirani, R. (1986). Generalized additive models (with discussion). Statist. Sci., 297– 318. Retrieved from https://web.stanford.edu/~hastie/Papers/gam.pdf
27 Hill, J. (2013). Hedonic Price Indexes for Residential Housing: A Survey, Evaluation and Taxonomy. Retrieved from https://www.researchgate.net/publication/263259181_Hedonic_Price_Indexes_for_Residenti al_Housing_A_Survey_Evaluation_and_Taxonomy Kestens Y., Thériault M., Rosiers, F. (2006). Heterogeneity in hedonic modelling of house prices: Looking at buyers' household profiles, February 2006 Journal of Geographical Systems , 61-96. Kain, J. & Quigley, J. (1970). Measuring the Value of Housing Quality. Journal of the American Statistical Association, 65, 532-548. Mason, C., & Quigley, J., M. (1996). Non-parametric hedonic housing prices. Retrieved from https://escholarship.org/uc/item/2qz3t9n2 Malpezzi, S. (2003). Hedonic pricing models: A selective and applied review. In T. O’Sullivan & K. Gibb (Eds.), Housing economics and public policy, 67–89. McMillen, D., P. & Redfearn, C. L. (2010). Estimation and Hypothesis Testing for Nonparametric Hedonic House Price Functions, Journal of Regional Science, Vol. 50, No. 3, 712-733. McCullagh, P. and Nelder, J.A. (1989). Generalized Linear Models. 2nd Edition, Chapman and Hall, London, 8. Meen, G., (2001). Modelling Spatial Housing Markets. Rodriguez, M. & Sirmans, F. (1994). Quantifying the Value of a View in Single Family Housing Markets, The Appraisal Journal, 600–03. Sirmans, G., Zietz, E., David A. (2006). The Composition of Hedonic Pricing Models. Sirpal, R., (1994). Empirical Modeling of the Relative Impacts of Various Sizes of Shopping Centers on the Values of Surrounding Residential Properties, Journal of Real Estate Research, American Real Estate Society, vol. 9(4), 487-506. Wallace, N. (1991). The Construction of Residential Housing Price Indices: A Comparison of Repeat- Sales, Hedonic-Regression, and Hybrid Approaches. Retrieved from https://ideas.repec.org/a/kap/jrefec/v14y1997i1-2p51-73.html Wallace, N. (1996). Hedonic-based price indexes for housing: theory, estimation, and index construction. Retrieved from https://www.frbsf.org/economic-research/files/wallace.pdf Waugh, F.V. (1928). Quality factors influencing vegetable prices, Journal of Farm Economics,10. 185– 196. Wolfgang B. (2010). Spatial Heterogeneity in Hedonic House Price Models: The Case of Austria. Wood, S. N. (2004). Stable and efficient multiple smoothing parameter estimation for generalized additive models. Journal of the American Statistical Association 99, 673–686. Wood, S. N., (2006). An introduction to generalized additive models with R CRC Press.
28 Wood, S.N. (2000). Modelling and smoothing parameter estimation with multiple quadratic penalties Journal of the Royal Statistical Society: Series B, 62, 413-428. Wood, S.N. (2012). mgcv: Mixed GAM Computation Vehicle with GCV/AIC/REML smoothness estimation.
29 9. APPENDIX 9.1. MGCV PACKAGE USABILITY Splines: Does not support loess or smoothing splines, but supports a wide array of regression splines (P-splines, B-splines, thin plate splines, tensors) + tensors Parametric terms: Supported, and you can penalize or treat as random effects, PIRLS, Finds smoothing parame. Variable selection: Shrinkage Optimization: PIRLS Selecting smoothing: Finds smoothing parameters by default. Supports, both REML and GCV Large datasets: Special bam function for large datasets. Missing values: No special treatment. Omits observations missing values Multidimensional: Supported with tensors and thin plate splines Model diagnostics: Standard GAM diagnostics + the concurvity measure which is a generalization of collinearity 9.2. OFFSET INPUTS name wert efh 1 cond3_haus_gut 0.03 1 2 cond1_haus_schlecht -0.05 1 3 cond3_gut 0.02 0 4 cond1_schlecht -0.04 0 5 sauna 0.02 1 6 barrierefrei 0.02 1 7 alarmanlage 0.01 1 8 swimmingpool 0.02 1 9 zentral 0.01 1 10 abstellraum 0.01 1 11 wintergarten 0.01 1 12 zentral_fern_etage 0.01 1 13 parkett 0.01 1 14 garage 0.01 1 15 stell 0 1 16 villa 0.02 1 17 cell 0.01 1 18 garten 0.01 1 Table 9-1: Model Offset Values
30 9.3. DATA IMPUTATION R CODE hyper_grid_2 <- expand.grid( mtry = seq(1, 20, by = 1), num.trees = seq(50, 500, by = 50), OOB_RMSE = 0) default_model <- ranger::ranger(formula, training , splitrule="variance", mtry=7, importance = "impurity", num.threads = 6 ,num.trees = 200, write.forest = T) default <- sqrt(default_model$prediction.error) for(i in 1:nrow(hyper_grid_2)) { impute_model <- ranger::ranger(formula, training , splitrule="variance", mtry=hyper_grid_2$mtry[i], importance = "impurity", num.threads = 6 ,num.trees = hyper_grid_2$num.trees[i], write.forest = T, respect.unordered.factors = "order") hyper_grid_2$OOB_RMSE[i] <- sqrt(impute_model$prediction.error) } hyper_grid_2 %>% arrange(OOB_RMSE) %>% mutate(perc_gain = (default - OOB_RMSE) / default * 100) %>% head(10) hyper_grid_2 %>% dplyr::arrange(OOB_RMSE) %>% head(10) hist(hyper_grid_2$OOB_RMSE, breaks = 20) impute_model$variable.importance %>% # tidy() %>% dplyr::arrange(desc(x)) %>% dplyr::top_n(25) %>% ggplot(aes(reorder(names, x), x)) + geom_col() + coord_flip() + ggtitle("Top 25 important variables") pred <- predict(impute_model$forest, data[is.na(data[[var]]),] ) data[, paste0(var,"_imputed")] <- data[,var]
31 9.4. FITTED MODEL DATA EXPLORATION 9.4.1. Correlation Table 9.4.2. Density Functions Figure 9-1: Correlation among variables Figure 9-2: Correlation between variables log m² price Figure 9-3: log m² price – log area density distribution
32 9.4.3. Distribution for Furnshing 9.5. BASE FORMEL PREPARATION nam_vz <- list(); vz <- list() nam_vz_base <- c( "gar", "stell", "balc", "garten", "cell", "loggia", "wintergarten", "zentral_fern_etage", "Rating”,"saniert") sign_base <- c(1,1, 1,1,1,1,1, 1,-1, 1) # Specific EFH nam_vz[["efh"]] <- c(nam_vz_base, "villa", "efh_bp") vz[["efh"]] <- c(sign_base, 1, 1) # Collect in list sign_vz <- list() for (nam in names(vz)) { print(nam) sign_vz[[nam]] <- assign_signs(nam = nam_vz[[nam]], vz = vz[[nam]])} nam_ovz_base <- c("ausstattung_fac") nam_ovz <- list() nam_ovz[["efh"]] <- c(nam_ovz_base, "rh", "dhh") vars_select_all <- list() for (nam in names(vz)) { print(nam) vars_select_all[[nam]] <- c(nam_vz[[nam]], nam_ovz[[nam]]) } Figure 9-4: – furnishing effect on log m² price
33 9.6. XGBOOST – RESIDUAL MODEL model_residuals_efh <- function(data){ if (is.null(data$residual)){ stop("Add the residuals first!!!") } cols <- c("ln_plot", "age", "ln_area", "quarter", "efh_bp", "PLZ1", "Rating", "zentral_fern_etage", "ausstattung_fac", "gar", "cell", "garten", "saniert", "balc") covariates <- data[ , cols] data <- data[!is.na(data$Rating) , ] model <- xgboost::xgboost(data = data.matrix(covariates), label = data$residual , max_depth = 8, gamma=0, colsample_bytree = 1, min_child_weight = 1, subsample = 1 , eta = 0.1, nthread = 8, nrounds = 2000, objective = "reg:squarederror" , verbose = 0) return(model) } For (i in 1:length(d1$lnp_qm)) { if(d1$lnp_qm[i] - m1$model[i,"lnp_qm"] != 0) { print(i) d1 <- d1[-c(i),] break; } } d1$residual <- m1$residual cols <- c("ln_plot", "age", "ln_area", "quarter", "efh_bp", "PLZ1", "Rating", "zentral_fern_etage", "ausstattung_fac", "gar", "cell", "garten", "saniert", "balc") covariates <- data.matrix(d1[ !is.na(d1$Rating), cols]) pred_train_xg <- predict(xg_error_model,covariates) cols <- c("ln_plot", "age", "ln_area", "quarter", "efh_bp", "PLZ1", "Rating", "zentral_fern_etage", "ausstattung_fac", "gar", "cell", "garten", "saniert", "balc") covariates <- data.matrix(test_df[ !is.na(test_df$Rating), cols]) pred_test_xg <- predict(xg_error_model , covariates) 9.7. SELECTED MODEL OUTPUT 9.7.1. GAM Model (GCV / TP) Family: gaussian Link function: identity Formula: lnp_qm ~ s(KGS05a, bs = "re") + s(PLZ1, bs = "re", by = by_plz) + s(ln_area) + s(ln_plot) + s(age) + year_fac + s(quarter, bs = "re") + offset(offset_cond) + gar + stell + balc + garten + cell + loggia + wintergarten + zentral_fern_etage + Rating + saniert + villa + efh_bp + ausstattung_fac + rh + dhh Parametric coefficients: