Tensorflow 如何与 Estimators 配合使用来优化模型?

tensorflowserver side programmingprogramming更新于 2025/5/20 5:22:17

添加特定列后,可以优化与 titanic 数据集相关的模型,以获得更好的性能。一旦添加并训练了列,并且评估了模型,模型就会被优化,从而提供更好的性能。

阅读更多: 什么是 TensorFlow,以及 Keras 如何与 TensorFlow 配合使用来创建神经网络?

我们将使用 Keras Sequential API,它有助于构建一个顺序模型,该模型用于处理普通的层堆栈,其中每个层都有一个输入张量和一个输出张量。

包含至少一个层的神经网络称为卷积层。我们可以使用卷积神经网络构建学习模型。

我们使用 Google Colaboratory 运行以下代码。Google Colab 或 Colaboratory 有助于在浏览器上运行 Python 代码,无需配置,可以免费访问 GPU(图形处理单元)。Colaboratory 建立在 Jupyter Notebook 之上。

估算器是 TensorFlow 对完整模型的高级表示。它旨在轻松扩展和异步训练。估算器使用特征列来描述模型如何解释原始输入特征。估算器需要数字输入向量,而特征列将有助于描述模型应如何转换数据集中的每个特征。

示例

print("The model is optmised to make predictions on a dataset")
pred_dicts = list(linear_est.predict(eval_input_fn))
probs = pd.Series([pred['probabilities'][1] for pred in pred_dicts])
print("The data is plotted")
probs.plot(kind='hist', bins=20, title='predicted probabilities')

代码来源 −https://www.tensorflow.org/tutorials/estimator/linear

输出

The model is optmised to make predictions on a dataset
INFO:tensorflow:Calling model_fn.
WARNING:tensorflow:Layer linear/linear_model is casting an input tensor from dtype float64 to the layer's dtype of float32, which is new behavior in TensorFlow 2. The layer has dtype float32 because its dtype defaults to floatx.
If you intended to run this layer in float32, you can safely ignore this warning. If in doubt, this warning is likely only an issue if you are porting a TensorFlow 1.X model to TensorFlow 2.
To change all layers to have dtype float64 by default, call `tf.keras.backend.set_floatx('float64')`. To change just this layer, pass dtype='float64' to the layer constructor. If you are the author of this layer, you can disable autocasting by passing autocast=False to the base Layer constructor.
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from /tmp/tmpg17o3o7e/model.ckpt-200
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
<matplotlib.axes._subplots.AxesSubplot at 0x7f8e2c1dd358>
The data is plotted

解释

  • 准确率达到 77.6%,比在基础特征上训练的准确率更高。

  • 可以应用更多特征和转换来查看模型是否表现更好。

  • 该模型经过训练,可从评估集中对乘客进行预测。

  • TensorFlow 模型经过优化,可对批量或一次性收集的示例进行预测。


相关文章