利用tensorflow进行房价预测

一.理论基础

1.什么是tensorflow?

TensorFlow 是由 Google 团队开发的深度学习框架之一,它是一个完全基于 Python 语言设计的开源的软件。TensorFlow 的初衷是以最简单的方式实现机器学习和深度学习的概念,它结合了计算代数的优化技术,使它便计算许多数学表达式。

2.什么是tensorflow decision forests?

TensorFlow 决策森林 (TF-DF) 是一套先进的算法,可用于训练、应用和解释决策森林模型。该库包含一套 Keras 模型,并且支持分类、回归和排名。

 3.什么是决策树

决策树是一种有监督的机器学习,每个节点都代表一个自变量,即特征,节点之间联系代表一个决策过程,叶节点代表一个结果,决策树主要分为分类树和回归树,在此房价预测中使用了随机森林模型。除此以外还有

  • GradientBoostedTreesModel:梯度提升算法模型,先训练一个基学习器,再根据其表现调整模型使模型残差沿梯度方向降低(较为耗时)
  • CartModel
  • DistributedGradientBoostedTreesModel

4.什么是集成学习

在机器学习的有监督学习算法中,集成学习是组合这里的多个弱监督模型以得到更好更全面的强监督模型。

集成学习的分类:

  • Bagging:利用bootstep方法从整体数据集中有放回的抽样得到N个数据集,在每个数据集上学习一个模型,最后结果是N个模型输出平均,例如随机森林。
  • Boosting:每次计算都减少上一次的残差
  • Stackling:先训练多个不同模型,然后把之前训练的各个模型的输出作为输入来训练一个模型

5.什么是随机森林?

随机森林是一种主流的决策森林模型,特征选择是构造决策树的理论依据。其一般有三种量化方法:

(1)信息增益

信息增益是表示数据集中某个特征X的信息使类Y的信息的不确定性减少的程度,即特征X让类Y不确定度降低。特征A对训练数据集D的信息的信息增益?(D,A),定义为集合D的HD)与特征A给定条件下D的条件H(D A)之差8(D, A) = H(D) - H(D|A)其中H(D)和H(DA)之差成为互信息。

(2)信息增益率

既然信息增益偏向值个数多的属性,那我们就给值多的属性进行"惩罚"。利用tensorflow进行房价预测_第1张图片

(3)基尼系数

基尼系数反映了随机抽取两个样本,其类别不一致的概率。我们的目的是使同一个分支的类别一致,而基尼系数反映的是分支内任意两个样本分类不一致的情况,所以基尼系数越小,分类越纯,所以我们选取基尼系数最小的属性作为最优划分属性。

利用tensorflow进行房价预测_第2张图片

 二.实现流程

1.Import the library

import tensorflow as tf
import tensorflow_decision_forests as tfdf
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# Comment this if the data visualisations doesn't work on your side
%matplotlib inline

2.Load the dataset

train_file_path = "../input/house-prices-advanced-regression-techniques/train.csv"
dataset_df = pd.read_csv(train_file_path)
print("Full train dataset shape is {}".format(dataset_df.shape)

3.查看数据信息并预处理

dataset_df.head(3)
dataset_df = dataset_df.drop('Id', axis=1)
dataset_df.head(3)
dataset_df.info()
print(dataset_df['SalePrice'].describe())
plt.figure(figsize=(9, 8))
sns.distplot(dataset_df['SalePrice'], color='g', bins=100, hist_kws={'alpha': 0.4});

4.Numerical data distribution

rf = tfdf.keras.RandomForestModel(task = tfdf.keras.Task.REGRESSION)
rf.compile(metrics=["mse"]) # Optional, you can use this to include a list of eval metrics
list(set(dataset_df.dtypes.tolist()))
df_num = dataset_df.select_dtypes(include = ['float64', 'int64'])
df_num.head()
df_num.hist(figsize=(16, 20), bins=50, xlabelsize=8, ylabelsize=8);

5.Prepare the dataset

import numpy as np
#将数据集分为训练集和测试集
def split_dataset(dataset, test_ratio=0.30):
  test_indices = np.random.rand(len(dataset)) < test_ratio
  return dataset[~test_indices], dataset[test_indices]

train_ds_pd, valid_ds_pd = split_dataset(dataset_df)
print("{} examples in training, {} examples in testing.".format(
    len(train_ds_pd), len(valid_ds_pd)))

6.Create a Random Forest

label = 'SalePrice'
train_ds = tfdf.keras.pd_dataframe_to_tf_dataset(train_ds_pd, label=label, task = tfdf.keras.Task.REGRESSION)
valid_ds = tfdf.keras.pd_dataframe_to_tf_dataset(valid_ds_pd, label=label, task = tfdf.keras.Task.REGRESSION)

7.Train the model

rf.fit(x=train_ds)

8.Evaluate the model on the Out of bag (OOB) data and the validation dataset 

我们还可以使用开箱(OOB)分数来验证我们的RandomForestModel。为了训练随机森林模型,算法从训练集中选择一组随机样本,其余样本用于微调模型。未选择的数据子集称为行李外数据(OOB)。OOB得分是根据OOB数据计算的。

import matplotlib.pyplot as plt
logs = rf.make_inspector().training_logs()
plt.plot([log.num_trees for log in logs], [log.evaluation.rmse for log in logs])
plt.xlabel("Number of trees")
plt.ylabel("RMSE (out-of-bag)")
plt.show()

利用tensorflow进行房价预测_第3张图片

inspector = rf.make_inspector()
inspector.evaluation()

 让我们使用验证数据集运行一个评估。

evaluation = rf.evaluate(x=valid_ds,return_dict=True)

for name, value in evaluation.items():
  print(f"{name}: {value:.4f}")

9.Variable importances

变量重要性通常表示特征对模型预测或质量的贡献程度。有几种方法可以使用TensorFlow决策森林来识别重要特征。让我们列出决策树可用的变量重要性:

print(f"Available variable importances:")
for importance in inspector.variable_importances().keys():
  print("\t", importance)

Available variable importances:
	 INV_MEAN_MIN_DEPTH
	 NUM_AS_ROOT
	 NUM_NODES
	 SUM_SCORE

例如,让我们显示变量重要性NUM_As_ROOT的重要功能。NUM_AS_ROOT的重要性得分越大,它对模型结果的影响就越大。默认情况下,列表按从最重要到最不重要的顺序排列。从输出中,您可以推断,与任何其他功能相比,列表顶部的功能被用作随机林中大多数树的根节点。

inspector.variable_importances()["NUM_AS_ROOT"]
[("OverallQual" (1; #62), 121.0),
 ("GarageCars" (1; #32), 49.0),
 ("ExterQual" (4; #22), 40.0),
 ("Neighborhood" (4; #59), 35.0),
 ("GrLivArea" (1; #38), 21.0),
 ("GarageArea" (1; #31), 15.0),
 ("BsmtQual" (4; #14), 7.0),
 ("YearBuilt" (1; #76), 5.0),
 ("KitchenQual" (4; #44), 4.0),
 ("TotalBsmtSF" (1; #73), 3.0)]

Plot the variable importances from the inspector using Matplotlib

plt.figure(figsize=(12, 4))

# Mean decrease in AUC of the class 1 vs the others.
variable_importance_metric = "NUM_AS_ROOT"
variable_importances = inspector.variable_importances()[variable_importance_metric]

# Extract the feature name and importance values.
#
# `variable_importances` is a list of  tuples.
feature_names = [vi[0].name for vi in variable_importances]
feature_importances = [vi[1] for vi in variable_importances]
# The feature are ordered in decreasing importance value.
feature_ranks = range(len(feature_names))

bar = plt.barh(feature_ranks, feature_importances, label=[str(x) for x in feature_ranks])
plt.yticks(feature_ranks, feature_names)
plt.gca().invert_yaxis()

# TODO: Replace with "plt.bar_label()" when available.
# Label each bar with values
for importance, patch in zip(feature_importances, bar.patches):
  plt.text(patch.get_x() + patch.get_width(), patch.get_y(), f"{importance:.4f}", va="top")

plt.xlabel(variable_importance_metric)
plt.title("NUM AS ROOT of the class 1 vs the others")
plt.tight_layout()
plt.show()

利用tensorflow进行房价预测_第4张图片10.predict

test_file_path = "../input/house-prices-advanced-regression-techniques/test.csv"
test_data = pd.read_csv(test_file_path)
ids = test_data.pop('Id')

test_ds = tfdf.keras.pd_dataframe_to_tf_dataset(
    test_data,
    task = tfdf.keras.Task.REGRESSION)

preds = rf.predict(test_ds)
output = pd.DataFrame({'Id': ids,
                       'SalePrice': preds.squeeze()})

output.head()

你可能感兴趣的:(tensorflow,python,随机森林)