tensorflow Estimator
1.Estimator是Tensorflow完整模型的高级表示,它被设计用于轻松拓展和 异步训练
2. 在Tensorflow2.0 kerasAPI 可以完成许多相同的任务,而且被认为是一个更容易学习的API
3. 设定好了数据 后,可以使用Tensorflow Estimator定义模型。
4. Estimator是从tf.estimator.Eatimator派生的任何类。 Tensorflow提供了一组tf.estimator来实现常见的机器学习算法。此外,也可以编写自己自定义的Estimator.
5. 为了编写基于预创建的Estimator的项目,必须完成以下工作:
a. 创建一个或多个输入函数
b.定义模型的特征列
c.实例化一个Estimator,指定特征列和各种超参数
d.在Estimator对象上调用一个或多个方法,传递合适的输入函数以作为数据源。
a.
必须创建输入函数来提供训练、评估和预测数据
输入函数是一个返回tf.data.Dataset
对象的函数,此对象会输出下列含两个元素的元组
(features,label)
features :
Python 字典
key:特征名称
value:包含此特征所有值的==数组==
label:包含每个样本的标签的值的==数组==
def input_evaluation_set():
features = {'SepalLength':np.array([6.4,5.0]),
'SepalWidth':np.array([2.8,2.3]),
'PetalLength':np.array([5.6,3.3]),
'PetalWidth':np.array([2.2,1.0])}
labels = np.array([2,1])
return features,labels
输入函数可以以我喜欢的方式生成features字典和label列表
b
特征列是一个对象,用于描述模型应该如何使用特征字典中的原始输入数据。
当构建一个Estimator模型的时候,会向其传递一个特征列的列表,其中包含希望模型使用的每个特征
tf.feature_column
模块特工了徐国为模型表示数据的选项。
特征列描述了如何使用输入
my_feature_columns = []
for key in train.keys():
print(tf.feature_column.numeric_column(key = key))
my_feature_columns.append(tf.feature_column.numeric_column(key = key))
c
tf.estimator.DNNClassifier
多类别分类
tf.estimator.DNNLinearCombinedClassifier
用于广度与深度模型
tf.estimator.LinearClassifier
基于线性模型的分类器
d.在Estimator对象上调用一个或多个方法,传递合适的输入函数以作为数据源。
train
evaluate
predict
都要有input_fn函数
1.通过调用Estimator的Train
方法来训练模型
def input_fn(features,labels,training = True, batch_size = 256):
"""An input function for training or evaluating"""
#将输入转换为数据集
dataset = tf.data.Dataset.from_tensor_slices((dict(features),labels))
#如果在训练模式下混淆并重复数据
if training:
dataet = dataset.shuffle(1000).repeat()
return dataset.batch(batch_size)
XXX.train(input_fn = lambda: input_fn(train[pd.DataFrame],train_y[pandas.core.series.Series],training = False),steps = 50000)
注意input_fn
调用封装在lambda
中以获取参数,同时提供不带参数
的函数
2经过训练后,可以评估模型evaluate
方法
如果不指定steps 参数,用于评估的input_fn只生成一个epoch的数据
reutrn A dict containing the evaluation metrics specified in `model_fn` keyed by
name, as well as an entry `global_step` which contains the value of the
global step for which this evaluation was performed. For canned
estimators, the dict contains the `loss` (mean loss per mini-batch) and
the `average_loss` (mean loss per sample). Canned classifiers also return
the `accuracy`. Canned regressors also return the `label/mean` and the
`prediction/mean`.
3.利用经过训练的模型进行预测predict
方法
predict
方法返回一个Python可迭代对象,为每个样本生成一个预测结果字典
,输出概率
‘logits’: array([ 0.4225917, -2.0695136, -2.1001966], dtype=float32),
‘probabilities’: array([0.8598665 , 0.07114158, 0.06899188], dtype=float32),
‘class_ids’: array([0]),
‘classes’: array([b’0’], dtype=object),
‘all_class_ids’: array([0, 1, 2], dtype=int32),
‘all_classes’: array([b’0’, b’1’, b’2’], dtype=object)}
从Keras 模型到Estimator模型
1.Tensorflwo Estimators are fully supported in Tensorflow,
and can be created form new adn existing tf.keras models
2.Estimators need control of when and how their input pipeline is built.
To allow this, they require an “input function” or input_fn
.
The Estimator
will call this function with no arguments.
The input_fn
must return a tf.data.Dataset
3.A tf.keras.Model
can be trained with the tf.eatimator
API by converting the model to an
tf.estimator.Estimator
object with tf.keras.estimator.model_to_estimator