TensorFlow 是由 Google 团队开发的深度学习框架之一,它是一个完全基于 Python 语言设计的开源的软件。TensorFlow 的初衷是以最简单的方式实现机器学习和深度学习的概念,它结合了计算代数的优化技术,使它便计算许多数学表达式。
TensorFlow 决策森林 (TF-DF) 是一套先进的算法,可用于训练、应用和解释决策森林模型。该库包含一套 Keras 模型,并且支持分类、回归和排名。
决策树是一种有监督的机器学习,每个节点都代表一个自变量,即特征,节点之间联系代表一个决策过程,叶节点代表一个结果,决策树主要分为分类树和回归树,在此房价预测中使用了随机森林模型。除此以外还有
在机器学习的有监督学习算法中,集成学习是组合这里的多个弱监督模型以得到更好更全面的强监督模型。
集成学习的分类:
随机森林是一种主流的决策森林模型,特征选择是构造决策树的理论依据。其一般有三种量化方法:
信息增益是表示数据集中某个特征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)之差成为互信息。
既然信息增益偏向值个数多的属性,那我们就给值多的属性进行"惩罚"。
基尼系数反映了随机抽取两个样本,其类别不一致的概率。我们的目的是使同一个分支的类别一致,而基尼系数反映的是分支内任意两个样本分类不一致的情况,所以基尼系数越小,分类越纯,所以我们选取基尼系数最小的属性作为最优划分属性。
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
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)
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});
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);
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)))
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)
rf.fit(x=train_ds)
我们还可以使用开箱(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()
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}")
变量重要性通常表示特征对模型预测或质量的贡献程度。有几种方法可以使用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()
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()