1. 高效流水线。数据处理和生成的实用原理。 1. 前言
上一篇博文的一大篇,数据处理,今天介绍一个用于模型构建和简化流程的高级API。
2.优势
本文档介绍了一种高级 API,可极大地简化机器学习编程。您将获得无数好处。
简化了模型开发人员之间共享实现的过程。您可以使用高级直观代码开发高级模型。简而言之,采用创建模型通常比采用低级 API 更简单。它本身是建立在 tf.以简化定制过程。 3.预创建
def input_fn(dataset):
# manipulate dataset, extracting the feature dict and the label
return feature_dict, label
# Define three numeric feature columns.
population = tf.feature_column.numeric_column('population')
crime_rate = tf.feature_column.numeric_column('crime_rate')
median_education = tf.feature_column.numeric_column('median_education',
normalizer_fn=lambda x: x - global_education_mean)
# Instantiate an estimator, passing the feature columns.
estimator = tf.estimator.LinearClassifier(
feature_columns=[population, crime_rate, median_education],
)
# my_training_set is the function created in Step 1
estimator.train(input_fn=my_training_set, steps=2000)
4.自定义.1输入函数
输入函数可以直接返回,标签,或者.or(),所以和我们高效的数据预处理联系在一起。
def input_fn(features, labels, batch_size):
"""An input function for training"""
# Convert the inputs to a Dataset.
dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))
# Shuffle, repeat, and batch the examples.
dataset = dataset.shuffle(1000).repeat().batch(batch_size)
# Return the read end of the pipeline.
return dataset.make_one_shot_iterator().get_next()
4.2 创建特征列
您必须定义模型的特征列以指定模型应如何使用每个特征。无论您使用预先创建的还是自定义的,您定义特征列的方式都是相同的。
以下代码为每个输入特征创建一个简单的,表示输入特征的值应该直接作为模型的输入:
# Feature columns describe how to use the input.
my_feature_columns = []
for key in train_x.keys():
my_feature_columns.append(tf.feature_column.numeric_column(key=key))
4.3 模型函数
def model_fn(
features, # This is batch_features from input_fn
labels, # This is batch_labels from input_fn
mode, # An instance of tf.estimator.ModeKeys
params): # Additional configuration
前两个参数是输入函数返回的和,mode参数表示调用程序正在请求训练、预测或估计。因此,需要实现三种请求方法:训练、预测和评估。
调用程序可以传递给的构造函数。传递给构造函数的所有内容都会依次传递给 .
classifier = tf.estimator.Estimator(
model_fn=my_model,
params={
'feature_columns': my_feature_columns,
# Two hidden layers of 10 nodes each.
'hidden_units': [10, 10],
# The model must choose between 3 classes.
'n_classes': 3,
})
5.定义模型5.1 定义输入层
在第一行调用 tf。 .,为了将特征字典和转换为模型的输入,应用特征列定义的转换,创建模型的输入层。如下:
# Use `input_layer` to apply the feature columns.
net = tf.feature_column.input_layer(features, params['feature_columns'])
5.2 个隐藏层
如果您要创建深度神经网络,则必须定义一个或多个隐藏层。 API 提供了一组丰富的函数来定义所有类型的隐藏层,包括卷积层、池化层和 层。
隐藏层是用户可以发挥想象力并定义复杂的地方。
# Build the hidden layers, sized according to the 'hidden_units' param.
for units in params['hidden_units']:
net = tf.layers.dense(net, units=units, activation=tf.nn.relu)
5.3个输出层
# Compute logits (1 per class).
logits = tf.layers.dense(net, params['n_classes'], activation=None)
@ >
tf.nn.函数将这些对数转换为概率。
5.4 实施训练、评估和预测
创建模型函数的最后一步是编写预测、评估和训练分支代码的实现。
关注第三个参数模式。如下表所示,当有人调用train,或者框架调用model函数,设置mode参数为.TRAIN, .EVAL, .
模型函数必须提供代码来处理所有三个模式值。对于每个模式值,您的代码必须返回一个 tf.. 实例,其中包含调用程序所需的信息。让我们仔细看看每种模式。
构建训练操作需要优化器。我们将使用 tf.train..
我们使用优化器的方法,根据我们之前计算的损失构造一个训练操作。
该方法也有参数。
optimizer = tf.train.AdagradOptimizer(learning_rate=0.1)
train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())
if mode == tf.estimator.ModeKeys.TRAIN:
return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)
虽然返回指标是可选的。提供一个指标模块 tf.计算常用指标。为简单起见,我们将只返回准确度。
# Compute evaluation metrics.
accuracy = tf.metrics.accuracy(labels=labels,
predictions=predicted_classes,
name='acc_op')
metrics = {'accuracy': accuracy}
tf.summary.scalar('accuracy', accuracy[1])
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(
mode, loss=loss, eval_metric_ops=metrics)
必须训练模型才能进行预测。训练好的模型存储在磁盘上,在您实例化时创建的目录中。
该模型用于生成预测的代码如下:
# Compute predictions.
predicted_classes = tf.argmax(logits, 1)
if mode == tf.estimator.ModeKeys.PREDICT:
predictions = {
'class_ids': predicted_classes[:, tf.newaxis],
'probabilities': tf.nn.softmax(logits),
'logits': logits,
}
return tf.estimator.EstimatorSpec(mode, predictions=predictions)
存储了以下三个键值对:
p>
我们通过一个参数(tf..)将该字典返回给调用程序。该方法将生成这些字典。
6.实例化
通过实例化基类来自定义如下:
# Build 2 hidden layer DNN with 10, 10 units respectively.
classifier = tf.estimator.Estimator(
model_fn=my_model,
params={
'feature_columns': my_feature_columns,
# Two hidden layers of 10 nodes each.
'hidden_units': [10, 10],
# The model must choose between 3 classes.
'n_classes': 3,
})
< 这里,字典的用途与关键字参数相同;即使用字典,您可以在不修改代码的情况下进行配置。
使用其余代码来训练、评估和生成预测与预先创建的章节中的相同。例如,以下行将训练模型:
# Train the Model.
classifier.train(
input_fn=lambda:iris_data.train_input_fn(train_x, train_y, args.batch_size),
steps=args.train_steps)
7. 工作流假设存在一个合适的预创建模型,使用它来构建第一个模型并使用结果确定基准。使用这个预先创建的构建并测试您的整体管道,包括数据完整性和可靠性。如果存在其他合适的预创建,请运行实验以确定哪个预创建效果最好。可以通过构建自定义来进一步改进模型。
暂无评论内容