"Furnace AI" machine learning 006-building a price evaluation model with decision tree regression

Source: Internet
Author: User

"Furnace AI" machine learning 006-building a price evaluation model with decision tree regression

(Python libraries and version numbers used in this article: Python 3.5, Numpy 1.14, Scikit-learn 0.19, matplotlib 2.2)

In recent decades, housing prices have been the heart of Chinese people forever pain, it is said that China's housing prices are like women's strapless bra, half the people are wondering: what support it? The other half is waiting: When will it fall down? And a woman, never let it fall. Even if it fell off quickly, mention or go up again ...

While we cannot predict when Chinese house prices will collapse, but can use machine learning to build a housing price forecast model, we use the Boston house price data set to build a housing price assessment model, through the location of the house, population characteristics and other factors to evaluate the price.


1. Analyzing data sets

The data set used in this model is from the official website of the Boston house price dataset at: (http://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html).

This data set is small, only 506 samples, each sample has 13 features, 1 labels, the description of the 14 properties is as follows:

So we need to build the model, use the previous 13 features to evaluate the final Medv, even with 13 eigenvectors to calculate the price, this is a typical multivariate regression problem. Although the data set can be downloaded directly from the official web, the dataset is already integrated in Sklearn and can be called directly. The following code

# analysis DataSet from Sklearn import Datasets # Sklearn comes with datasets Boston rate DataSet Housing_data=datasets.load_boston () dataset_x= Housing_data.data # Gets the feature vector that affects the house price, as Feaure Xdataset_y=housing_data.target # gets the corresponding rate as label y# print (Dataset_x.shape) # ( 506, 13) # A total of 506 samples, each with 13 features# print (Dataset_y.shape) # (506,) # Print (Dataset_x[:5,:]) # prints to see the value type and size of features, Seems to have normalize.# the entire data set into train set and test set two parts from sklearn.utils import shuffledataset_x,dataset_y=shuffle (dataset_x , dataset_y) # Print (Dataset_x[:5,:]) # Confirm that dataset_x did happen Shufflenum_split=int (0.8*len (dataset_x)) train_x,train_y= dataset_x[:num_split],dataset_y[:num_split]test_x,test_y=dataset_x[num_split:],dataset_y[num_split:]# Print ( Train_x.shape) # (404,) # print (test_x.shape) # (102, 13) # The above data set partitioning can also take the following method: # from Sklearn.model_selection import Trai n_test_split# dataset_y=dataset_y[:,np.newaxis]# Dataset=np.hstack (dataset_x,dataset_y) # print (dataset.shape) # Print (Dataset[:,:3]) # Train_set,test_set=train_test_split (dataset,test_size=0.2,random_state=37) # Print (train_set.shape) # (404, +) # print (test_set.shape) # (102, 14) 

The code first calls Sklearn.load_boston () to get the Boston house price dataset and divides the dataset into two parts, where train set occupies 80% (404 samples) and test set occupies 20% (102 samples). When we look at the results of the five rows in the data set, we find that the entire dataset has been normalize, and we do not need to be normalized here.


2. Building a decision tree model

The decision tree (DecisionTree, DT) is a common non-parametric supervised learning method for classification and regression, and the goal is to create a model that predicts the value of a target variable by deriving a simple decision rule from the data attributes.

The advantages of the decision tree model are: 1, simple and easy to understand, the number of structures can be visualized expression. 2, requiring little data preparation, other techniques often require data normalization, need to create virtual variables, and remove blank values. 3, can handle multi-output problem. 4, the decision tree is a white box model compared to the model using neural network, the result is easy to explain.

The disadvantage of decision tree model is that: 1, decision tree Learning may generate overly complex number structure, can not represent the general rule, that is, the model is easy to fit, pruning mechanism, the minimum number of samples required to set the leaf node or the maximum depth of the set number is necessary to avoid decision tree overfitting. 2, the decision tree may be unstable because small changes in the data can result in a completely different tree generation. This problem can be mitigated by using multiple decision trees in a collection. 3, the actual decision tree Learning algorithm is based on heuristic algorithm, such as the greedy algorithm of local optimal decision on each node. This algorithm cannot guarantee the return of the global optimal decision tree. By training multiple trees in set learning, you can reduce this situation, where features and samples are randomly extracted. 4, some concepts are difficult to learn because decision trees cannot easily express them, such as XOR, parity, or multiplexing issues.

Say so much nonsense, read the code directly ...

# 构建决策树回归模型from sklearn.tree import DecisionTreeRegressordecision_regressor=DecisionTreeRegressor(max_depth=4) # 最大深度确定为4decision_regressor.fit(train_X,train_y) # 对决策树回归模型进行训练# 使用测试集来评价该决策树回归模型predict_test_y=decision_regressor.predict(test_X)import sklearn.metrics as metricsprint(‘决策树回归模型的评测结果----->>>‘)print(‘均方误差MSE:{}‘.format(    round(metrics.mean_squared_error(predict_test_y,test_y),2)))print(‘解释方差分:{}‘.format(    round(metrics.explained_variance_score(predict_test_y,test_y),2)))

-------------------------------------lose-----------------------------------------

Evaluation results of decision tree regression model----->>>
Mean square error mse:13.33
Explanatory square Differential: 0.81

--------------------------------------------finished-------------------------------------

####################### #小 ********** Knot ###############################

1. Decision tree regression model is very simple to build, similar to the construction of linear regression, using Decisiontreeregressor to obtain a regression object, model training using the FIT function, prediction using the Predict function.

2. The simple decision tree regression model obtained the MSE ratio is large, the interpretation square difference result is also not ideal, indicated that this model also has the big optimization space.

#################################################################


3. Optimization of decision tree model

In general, you can first optimize from the data set, but the data set of this project is a very mature case, the further optimization of the space is not big, so only from the model up and down hand. Here I use two optimization methods, the first is to optimize the decision tree model of various parameters, such as optimizing max_depth, to determine whether the MSE can be improved, the second way is to use the AdaBoost algorithm to enhance the accuracy of the model.

# 第一种优化方法:改变max depth来降低MSE,提高解释方差分for depth in range(2,12):    decision_regressor_test=DecisionTreeRegressor(max_depth=depth)     decision_regressor_test.fit(train_X,train_y)    predict_test_y2=decision_regressor_test.predict(test_X)    print(‘depth: {}, MSE: {:.2f}, EVS: {:.2f}‘.format(        str(depth), metrics.mean_squared_error(predict_test_y2,test_y),        metrics.explained_variance_score(predict_test_y2,test_y)))

-------------------------------------lose-----------------------------------------

Depth:2, mse:23.83, evs:0.62
Depth:3, mse:20.98, evs:0.68
Depth:4, mse:13.33, evs:0.81
Depth:5, mse:13.00, evs:0.83
Depth:6, mse:14.36, evs:0.83
Depth:7, mse:11.73, evs:0.86
Depth:8, mse:16.18, evs:0.83
Depth:9, mse:15.74, evs:0.83
Depth:10, mse:14.67, evs:0.83
Depth:11, mse:15.02, evs:0.84

--------------------------------------------finished-------------------------------------

# 第二种优化方法:通过AdaBoost算法来提高模型准确度from sklearn.ensemble import AdaBoostRegressorada_regressor=AdaBoostRegressor(DecisionTreeRegressor(max_depth=7),n_estimators=400)ada_regressor.fit(train_X,train_y)# 查看使用AdaBoost算法后模型的MSE 和EVSpredict_test_y=ada_regressor.predict(test_X)import sklearn.metrics as metricsprint(‘AdaBoost决策树回归模型的评测结果----->>>‘)print(‘均方误差MSE:{}‘.format(    round(metrics.mean_squared_error(predict_test_y,test_y),2)))print(‘解释方差分:{}‘.format(    round(metrics.explained_variance_score(predict_test_y,test_y),2)))

-------------------------------------lose-----------------------------------------

Evaluation results of AdaBoost decision tree regression model----->>>
Mean square error mse:7.87
Explanatory square Differential: 0.9

--------------------------------------------finished-------------------------------------

####################### #小 ********** Knot ###############################

1, two optimization methods: the first through the optimization of max_depth can be found in the depth=7 when the minimum MSE, and the interpretation of the maximum difference, it is determined max_depth=7.

2, the second through the AdaBoost enhancement algorithm to optimize the model, the MSE (7.87) is much smaller than the depth optimized MSE (11.73), and the interpretation of the difference also has a large increase, indicating that the optimization effect is better.

The 3,adaboost (Adaptive boosting) algorithm is an adaptive algorithm that uses other systems to enhance the accuracy of the model, combining the results of different versions of the algorithm and obtaining the final result in a weighted aggregate manner. The information obtained at each stage of the adaboost algorithm is fed back into the model, so that the learner can focus on the hard-to-classify samples at the latter stage.

4, of course, for this model, you can continue to optimize, such as the structure of the optimization decision tree, optimization of the decision tree and other parameters.

#################################################################


4. The relative importance of features

There are 13 characteristics of this project, but the impact of these 13 characteristics on house prices are certainly different, for example, from the intuitive point of view, the school district room on the impact of the house price is certainly relatively large, so you can calculate the impact of various characteristics on the model, and in the case of complex features, you can ignore the impact of relatively small features.

The next two parts of the code can draw the relative importance of various features to the diagram.

  # calculates the relative importance of different features Def plot_importances (Feature_importances, title, feature_names): " Plot the feature_importance into a chart to make it easier to observe and print out features that are more important than 5 "# will be important to 0-100 feature_importances=100.0* (Feature_importan Ces/max (feature_importances) # will score from high to low sort index_sorted=np.flipud (Np.argsort (feature_importances)) # Let the labels on the x axis Center display Pos=np.arange (index_sorted.shape[0]) +0.5 # Draw bar Chart plt.figure () Plt.bar (pos,feature_importances[index_so rted],align= ' center ') plt.xticks (pos,feature_names[index_sorted]) Plt.ylabel (' Relative importance ') Plt.title (tit Le) # prints out the importance result print (' {} importance list------>>>>> '. Format (title)) for Importance,name in Z IP (feature_importances[index_sorted], feature_names[index_sorted]): If importance> 5:print (' feature:{}, Importance: {:. 2f} '. Format (name,importance))  
decision_regressor7=DecisionTreeRegressor(max_depth=7) # 最大深度确定为7decision_regressor7.fit(train_X,train_y) # 对决策树回归模型进行训练plot_importances(decision_regressor7.feature_importances_,                 ‘DT regressor‘,housing_data.feature_names)plot_importances(ada_regressor.feature_importances_,                 ‘AdaBoost Optimized DT regressor‘,housing_data.feature_names)

-------------------------------------lose-----------------------------------------

DT regressor Importance list------>>>>>
Feature:lstat, importance:100.00
FEATURE:RM, importance:52.24
Feature:dis, importance:15.97
Feature:ptratio, importance:5.00
AdaBoost Optimized DT regressor importance list------>>>>>
Feature:lstat, importance:100.00
FEATURE:RM, importance:46.72
Feature:dis, importance:21.80
Feature:tax, importance:7.34
Feature:age, importance:7.29
Feature:crim, importance:6.51
Feature:nox, importance:5.32
Feature:ptratio, importance:5.29

--------------------------------------------finished-------------------------------------

####################### #小 ********** Knot ###############################

1, by comparison of the above two pictures, it can be seen that the relative importance of various characteristics of the model varies greatly, both models have found the most important feature is Lstat (which is different from the book "Python machine Learning classic example".

2, but the AdaBoost enhancement algorithm seems to be able to improve the relative importance of other small features, and the order of feature importance in both models is different.

#################################################################


Note: This section of the code has been uploaded to ( my GitHub), Welcome to download.

Resources:

1, Python machine learning classic example, Prateek Joshi, Tao Junjie, Chen Xiaoli translation

"Furnace AI" machine learning 006-building a price evaluation model with decision tree regression

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.