Tensorflow.Estimators学习笔记(1) - 介绍

本文深入探讨了TensorFlow的Estimators API,一种高级抽象工具,用于简化机器学习模型的构建、训练和评估过程。Estimators支持本地和分布式环境运行,提供模型共享便利,简化模型定制,并自动进行可视化。文章详细介绍了预制和定制Estimators的工作流程,以及如何从Keras模型创建Estimators。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Tensorflow.Estimators学习笔记 - 介绍

一、简介

estimators是tensorflow的机器学习高阶API:
包括四个部分:
1.1、训练
1.2、评估
1.3、预测
1.4、服务导出
该api基于类:tf.estimator.Estimator.

二、优势

estimator有以下优势:
2.1、基于estimator的模型既可以在本地运行,也可以在分布式环境中运行,可以不修改代码同时在CPU、TPU、GPU服务器上运行
2.2、轻便的实现模型开发者之间的共享
2.3、更简单的时间模型
2.4、estimator是简化订制在tf.layers
2.5、自动图像化
2.6、提供安全的训练循环:·图像化、·内置变量、·启动队列、·异常管理、·从错误中创建和删除测点文件

三、pre-made(预制)

预制能够让开发者从更高层面工作。预制estimator为开发者创造和管理图和会话对象。
3.1、预制estimators程序结构
3.1.1 写一个或多个数据集导入函数(返回一个特征数据字典、一个包含标签的tensor)

def input_fn(dataset):

   ...  # manipulate dataset, extracting the feature dict and the label

   return feature_dict, label

3.1.2 定义特征列
每一个tf.feature_column定义特征名、类型和任何输入预处理,举三个例子:

#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)

3.1.3 实例化预制estimator
举 LinearClassifier的例子:

#Instantiate an estimator, passing the feature columns.

estimator = tf.estimator.LinearClassifier(

    feature_columns=[population, crime_rate, median_education],

    )

3.1.4调用训练、评价、生成方法:
举train方法:

#my_training_set is the function created in Step 1

estimator.train(input_fn=my_training_set, steps=2000)

3.2、预制评估器的优势
指明计算图在计算机和计算集群中何处运行的最佳实践
普遍有用的事件总结最佳实践

四、订制评估器

订制评估器和预制评估器的核心,都是模型函数。

五、工作流推荐

5.1 假设合适的预制评估器存在,用它来构造第一个模型并建立基准线
5.2 构造和测试全局管道,包括对这个预制评估器的数据完整性和可靠性
5.3 对预制评估器做适当的修改,使他能够产生最佳结果
5.4 如果可以的话,建立自己的模型

六、从Keras models建立评估器

举例调用tf.keras.estimator.model_to_estimator:

 #Instantiate a Keras inception v3 model.
keras_inception_v3 = tf.keras.applications.inception_v3.InceptionV3(weights=None)
	 #Compile model with the optimizer, loss, and metrics you'd like to train with.
	keras_inception_v3.compile(optimizer=tf.keras.optimizers.SGD(lr=0.0001, momentum=0.9),
                           loss='categorical_crossentropy',
                          metric='accuracy')
 #Create an Estimator from the compiled Keras model. Note the initial model
 #state of the keras model is preserved in the created Estimator.
est_inception_v3 = tf.keras.estimator.model_to_estimator(keras_model=keras_inception_v3)
#Treat the derived Estimator as you would with any other Estimator.
#First, recover the input name(s) of Keras model, so we can use them as the
#feature column name(s) of the Estimator input function:
keras_inception_v3.input_names  # print out: ['input_1']
#Once we have the input name(s), we can create the input function, for example,
#or input(s) in the format of numpy ndarray:
train_input_fn = tf.estimator.inputs.numpy_input_fn(
     x={"input_1": train_data},
    y=train_labels,
     num_epochs=1,
    shuffle=False)
#To train, we call Estimator's train function:
est_inception_v3.train(input_fn=train_input_fn, steps=2000)
...
<think>好的,我现在需要解决用户的问题:如何在TensorFlow 2.x中替代tensorflow.contrib的功能和模块。首先,我得回顾一下tensorflow.contrib在1.x版本中的作用。这个模块包含了很多实验性的或社区贡献的代码,比如特定的层、优化器、RNN单元等。但在2.x中,这个模块被移除了,所以用户会遇到ModuleNotFoundError。 接下来,我需要根据提供的引用资料,找到替代的方法。首先,根据引用[3]和[4],TensorFlow 2.x集成了Keras,很多contrib中的功能已经被整合到核心库中。例如,像tf.contrib.rnn.LSTMCell现在应该用tf.keras.layers.LSTMCell替代,或者直接使用tf.compat.v1中的兼容API,但最好还是用新的Keras接口。 然后,用户提到的contrib中的其他模块,比如slim、layers、optimizers等。根据引用[5],建议使用tf.keras替代原有的层和模型构建方式。例如,contrib中的slim可以用Keras的层来替代,优化器可以使用tf.keras.optimizers中的类。 另外,一些特定功能可能需要查找是否有官方的替代方案。比如,tf.contrib.learn可能需要迁移到Keras的预训练模型或者使用TensorFlow Estimators,但Estimators在2.x中也不是推荐的方式,所以最好转用Keras。 然后,我需要整理这些替代方案,分点说明,确保用户能一步步找到替代方法。同时,要提到迁移工具如tf_upgrade_v2,以及使用tf.compat.v1作为临时解决方案,但强调推荐使用原生Keras API。 最后,生成相关问题,帮助用户进一步了解可能遇到的迁移问题。比如,如何处理特定的contrib模块,或者如何调整旧代码中的集合操作等。</think>在TensorFlow 2.x中替代`tensorflow.contrib`模块的解决方案可分为以下步骤: --- ### 1. **核心替代方案:使用官方API** TensorFlow 2.x将`contrib`中的常用功能整合到核心API中: - **RNN单元**:使用`tf.keras.layers`中的层,如`LSTMCell`、`GRUCell`替代`tf.contrib.rnn` ```python # TensorFlow 1.x cell = tf.contrib.rnn.LSTMCell(units=64) # TensorFlow 2.x cell = tf.keras.layers.LSTMCell(units=64) ``` - **优化器**:`tf.keras.optimizers`替代`tf.contrib.opt` 例如`AdamW`优化器迁移到`keras.optimizers.AdamW`[^3] - **损失函数与指标**:通过`tf.keras.losses`和`tf.keras.metrics`实现 --- ### 2. **特定模块迁移** 针对`contrib`中的子模块,可参考以下替代方案: - **tf.contrib.layers** → 完全由`tf.keras.layers`替代 例如`batch_norm`使用`tf.keras.layers.BatchNormalization` - **tf.contrib.slim** → 使用Keras的层或自定义模型结构 - **tf.contrib.learn** → 迁移到`tf.estimator`或直接使用Keras接口(推荐后者)[^5] --- ### 3. **兼容性临时方案** 若需短期兼容旧代码: - **启用V1兼容模式**:通过`tf.compat.v1`调用旧API ```python import tensorflow.compat.v1 as tf tf.disable_v2_behavior() ``` - **特定contrib组件**:部分功能保留在`tf.compat.v1.estimator`等子模块中[^4] --- ### 4. **代码迁移工具** 使用官方工具`tf_upgrade_v2`自动转换代码: ```bash tf_upgrade_v2 --infile=old_code.py --outfile=new_code.py ``` 该工具会将`tf.contrib.*`替换为等效API或标记需要手动修改的位置[^2]。 --- ### 5. **自定义实现** 对于无直接替代的组件(如某些统计工具): - 参考TensorFlow Addons库(`tfa`):提供实验性功能的官方扩展库 例如: ```python import tensorflow_addons as tfa optimizer = tfa.optimizers.MovingAverage(0.99) ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值