Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/zh-cn/guide/migrate/canned_estimators.ipynb
25118 views
Kernel: Python 3
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.

预设(或预制)Estimator 在 TensorFlow 1 中一直被用作一种快速简单的方式来针对各种典型用例训练模型。TensorFlow 2 通过 Keras 模型为其中一些方式提供了直接的近似替代。对于那些没有内置 TensorFlow 2 替代的预设 Estimator,您仍然能够相当轻松地构建自己的替代。

本指南将通过几个直接等效项和自定义替代示例来演示如何使用 Keras 将 TensorFlow 1 的 tf.estimator 派生模型迁移到 TensorFlow 2。

即,本指南包含下列迁移过程的示例:

  • 从 TensorFlow 1 中 tf.estimatorLinearEstimatorClassifierRegressor 到 TensorFlow 2 中的 Keras tf.compat.v1.keras.models.LinearModel

  • 从 TensorFlow 1 中 tf.estimatorDNNEstimatorClassifierRegressor 到 TensorFlow 2 中的自定义 Keras DNN ModelKeras

  • 从 TensorFlow 1 中 tf.estimatorDNNLinearCombinedEstimatorClassifierRegressor 到 TensorFlow 2 中的 tf.compat.v1.keras.models.WideDeepModel

  • 从 TensorFlow 1 中 tf.estimatorBoostedTreesEstimatorClassifierRegressor 到 TensorFlow 2 中的 tfdf.keras.GradientBoostedTreesModel in

模型训练的一个常见前身是特征预处理,可以使用 tf.feature_column 为 TensorFlow 1 Estimator 模型完成此过程。有关 TensorFlow 2 中特征预处理的更多信息,请参阅有关从特征列迁移到 Keras 预处理层 API 的本指南

安装

从几个必要的 TensorFlow 导入开始:

!pip install tensorflow_decision_forests
import keras import pandas as pd import tensorflow as tf import tensorflow.compat.v1 as tf1 import tensorflow_decision_forests as tfdf

从标准 Titanic 数据集中准备一些简单的数据进行演示:

x_train = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/train.csv') x_eval = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/eval.csv') x_train['sex'].replace(('male', 'female'), (0, 1), inplace=True) x_eval['sex'].replace(('male', 'female'), (0, 1), inplace=True) x_train['alone'].replace(('n', 'y'), (0, 1), inplace=True) x_eval['alone'].replace(('n', 'y'), (0, 1), inplace=True) x_train['class'].replace(('First', 'Second', 'Third'), (1, 2, 3), inplace=True) x_eval['class'].replace(('First', 'Second', 'Third'), (1, 2, 3), inplace=True) x_train.drop(['embark_town', 'deck'], axis=1, inplace=True) x_eval.drop(['embark_town', 'deck'], axis=1, inplace=True) y_train = x_train.pop('survived') y_eval = x_eval.pop('survived')
# Data setup for TensorFlow 1 with `tf.estimator` def _input_fn(): return tf1.data.Dataset.from_tensor_slices((dict(x_train), y_train)).batch(32) def _eval_input_fn(): return tf1.data.Dataset.from_tensor_slices((dict(x_eval), y_eval)).batch(32) FEATURE_NAMES = [ 'age', 'fare', 'sex', 'n_siblings_spouses', 'parch', 'class', 'alone' ] feature_columns = [] for fn in FEATURE_NAMES: feat_col = tf1.feature_column.numeric_column(fn, dtype=tf.float32) feature_columns.append(feat_col)

然后,创建一个方法来实例化一个简单的样本优化器,以便与我们的各种 TensorFlow 1 Estimator 和 TensorFlow 2 Keras 模型一起使用。

def create_sample_optimizer(tf_version): if tf_version == 'tf1': optimizer = lambda: tf.keras.optimizers.legacy.Ftrl( l1_regularization_strength=0.001, learning_rate=tf1.train.exponential_decay( learning_rate=0.1, global_step=tf1.train.get_global_step(), decay_steps=10000, decay_rate=0.9)) elif tf_version == 'tf2': optimizer = tf.keras.optimizers.legacy.Ftrl( l1_regularization_strength=0.001, learning_rate=tf.keras.optimizers.schedules.ExponentialDecay( initial_learning_rate=0.1, decay_steps=10000, decay_rate=0.9)) return optimizer

示例 1:从 LinearEstimator 迁移

TensorFlow 1:使用 LinearEstimator

在 TensorFlow 1 中,可以使用 tf.estimator.LinearEstimator 为回归和分类问题创建基线线性模型。

linear_estimator = tf.estimator.LinearEstimator( head=tf.estimator.BinaryClassHead(), feature_columns=feature_columns, optimizer=create_sample_optimizer('tf1'))
linear_estimator.train(input_fn=_input_fn, steps=100) linear_estimator.evaluate(input_fn=_eval_input_fn, steps=10)

TensorFlow 2:使用 Keras LinearModel

在 TensorFlow 2 中,可以创建 Keras tf.compat.v1.keras.models.LinearModel 的实例,它是 tf.estimator.LinearEstimator 的替代。tf.compat.v1.keras 路径用于表示预制模型的存在目的是兼容性。

linear_model = tf.compat.v1.keras.experimental.LinearModel() linear_model.compile(loss='mse', optimizer=create_sample_optimizer('tf2'), metrics=['accuracy']) linear_model.fit(x_train, y_train, epochs=10) linear_model.evaluate(x_eval, y_eval, return_dict=True)

示例 2:从 DNNEstimator 迁移

TensorFlow 1:使用 DNNEstimator

在 TensorFlow 1 中,可以使用 tf.estimator.DNNEstimator 为回归和分类问题创建基线深度神经网络 (DNN) 模型。

dnn_estimator = tf.estimator.DNNEstimator( head=tf.estimator.BinaryClassHead(), feature_columns=feature_columns, hidden_units=[128], activation_fn=tf.nn.relu, optimizer=create_sample_optimizer('tf1'))
dnn_estimator.train(input_fn=_input_fn, steps=100) dnn_estimator.evaluate(input_fn=_eval_input_fn, steps=10)

TensorFlow 2:使用 Keras 创建自定义 DNN 模型

在 TensorFlow 2 中,可以创建一个自定义 DNN 模型来替代由 tf.estimator.DNNEstimator 生成的模型,此模型具有类似级别的用户指定自定义(例如,与前面的示例一样,能够自定义选定的模型优化器)。

可以使用类似的工作流将 tf.estimator.experimental.RNNEstimator 替换为 Keras RNN 模型。Keras 通过 tf.keras.layers.RNNtf.keras.layers.LSTMtf.keras.layers.GRU 提供了许多内置的可自定义选项。要了解详情,请查看 使用 Keras 的 RNN 指南内置 RNN 层:简单示例部分。

dnn_model = tf.keras.models.Sequential( [tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(1)]) dnn_model.compile(loss='mse', optimizer=create_sample_optimizer('tf2'), metrics=['accuracy'])
dnn_model.fit(x_train, y_train, epochs=10) dnn_model.evaluate(x_eval, y_eval, return_dict=True)

示例 3:从 DNNLinearCombinedEstimator 迁移

TensorFlow 1:使用 DNNLinearCombinedEstimator

在 TensorFlow 1 中,可以使用 tf.estimator.DNNLinearCombinedEstimator 为回归和分类问题创建基线组合模型,并为其线性和 DNN 组件提供自定义能力。

optimizer = create_sample_optimizer('tf1') combined_estimator = tf.estimator.DNNLinearCombinedEstimator( head=tf.estimator.BinaryClassHead(), # Wide settings linear_feature_columns=feature_columns, linear_optimizer=optimizer, # Deep settings dnn_feature_columns=feature_columns, dnn_hidden_units=[128], dnn_optimizer=optimizer)
combined_estimator.train(input_fn=_input_fn, steps=100) combined_estimator.evaluate(input_fn=_eval_input_fn, steps=10)

TensorFlow 2:使用 Keras WideDeepModel

在 TensorFlow 2 中,可以创建 Keras tf.compat.v1.keras.models.WideDeepModel 的一个实例来替代由 tf.estimator.DNNLinearCombinedEstimator 生成的实例,此实例具有类似级别的用户指定自定义(例如,与前面的示例一样,能够自定义选定的模型优化器)。

WideDeepModel 是在 LinearModel 组件和自定义 DNN 模型的基础上构造的,这两者均已在前面的两个示例中进行了探讨。如果需要,也可以使用自定义线性模型来替代内置的 Keras LinearModel

如果您想构建自己的模型而不是预设 Estimator,请查看 Keras 序贯模型指南。有关自定义训练和优化器的更多信息,请参阅自定义训练:演示指南。

# Create LinearModel and DNN Model as in Examples 1 and 2 optimizer = create_sample_optimizer('tf2') linear_model = tf.compat.v1.keras.experimental.LinearModel() linear_model.compile(loss='mse', optimizer=optimizer, metrics=['accuracy']) linear_model.fit(x_train, y_train, epochs=10, verbose=0) dnn_model = tf.keras.models.Sequential( [tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(1)]) dnn_model.compile(loss='mse', optimizer=optimizer, metrics=['accuracy'])
combined_model = tf.compat.v1.keras.experimental.WideDeepModel(linear_model, dnn_model) combined_model.compile( optimizer=[optimizer, optimizer], loss='mse', metrics=['accuracy']) combined_model.fit([x_train, x_train], y_train, epochs=10) combined_model.evaluate(x_eval, y_eval, return_dict=True)

示例 4:从 BoostedTreesEstimator 迁移

TensorFlow 1:使用 BoostedTreesEstimator

在 TensorFlow 1 中,可以使用 tf.estimator.BoostedTreesEstimator 创建基线,以使用用于回归和分类问题的决策树集合创建一个基线梯度提升模型。TensorFlow 2 中不再包含此功能。

bt_estimator = tf1.estimator.BoostedTreesEstimator( head=tf.estimator.BinaryClassHead(), n_batches_per_layer=1, max_depth=10, n_trees=1000, feature_columns=feature_columns)
bt_estimator.train(input_fn=_input_fn, steps=1000) bt_estimator.evaluate(input_fn=_eval_input_fn, steps=100)

TensorFlow 2:使用 TensorFlow Decision Forests

在 TensorFlow 2 中,tf.estimator.BoostedTreesEstimatorTensorFlow Decision Forests 软件包中的 tfdf.keras.GradientBoostedTreesModel 所替代。

tf.estimator.BoostedTreesEstimator 相比,TensorFlow Decision Forests 具备多项优势,尤其是在质量、速度、易用性和灵活性方面。要了解 TensorFlow Decision Forests,请从初学者 colab 开始。

以下示例显示了如何使用 TensorFlow 2 训练梯度提升树模型:

安装 TensorFlow Decision Forests。

!pip install tensorflow_decision_forests

创建一个 TensorFlow 数据集。请注意,Decision Forests 原生支持多种类型的特征,不需要预处理。

train_dataframe = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/train.csv') eval_dataframe = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/eval.csv') # Convert the Pandas Dataframes into TensorFlow datasets. train_dataset = tfdf.keras.pd_dataframe_to_tf_dataset(train_dataframe, label="survived") eval_dataset = tfdf.keras.pd_dataframe_to_tf_dataset(eval_dataframe, label="survived")

train_dataset 数据集上训练模型。

# Use the default hyper-parameters of the model. gbt_model = tfdf.keras.GradientBoostedTreesModel() gbt_model.fit(train_dataset)

eval_dataset 数据集上评估模型的质量。

gbt_model.compile(metrics=['accuracy']) gbt_evaluation = gbt_model.evaluate(eval_dataset, return_dict=True) print(gbt_evaluation)

梯度提升树只是 TensorFlow Decision Forests 中可用的众多决策森林算法之一。例如,随机森林(以 tfdf.keras.GradientBoostedTreesModel 的形式提供,非常抗过拟合),而 CART(以 tfdf.keras.CartModel 的形式提供)则非常适合模型解释。

在下一个示例中,训练并绘制一个随机森林模型。

# Train a Random Forest model rf_model = tfdf.keras.RandomForestModel() rf_model.fit(train_dataset) # Evaluate the Random Forest model rf_model.compile(metrics=['accuracy']) rf_evaluation = rf_model.evaluate(eval_dataset, return_dict=True) print(rf_evaluation)

在最后一个示例中,训练和评估一个 CART 模型。

# Train a CART model cart_model = tfdf.keras.CartModel() cart_model.fit(train_dataset) # Plot the CART model tfdf.model_plotter.plot_model_in_colab(cart_model, max_depth=2)