tesorflowEstimator

本文介绍了如何将Keras模型转换为TensorFlow Estimator,强调了创建输入函数和特征列的重要性,以及Estimator在训练、评估和预测阶段的数据处理方式。通过Estimator的train, evaluate和predict方法,可以实现模型的生命周期管理。" 106737868,8685456,理解计算机网络:IP地址、子网与网络号详解,"['计算机网络', 'IP协议', '网络地址', '子网计算']

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


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

### 二维前缀和算法在瓦片图案生成或处理中的应用 #### 定义与基本原理 二维前缀和是一种用于快速求解矩形区域内元素总和的技术。对于给定的一个矩阵 `A`,可以预先计算一个新的矩阵 `prefixSum`,其中每个元素 `(i,j)` 表示从原点 `(0,0)` 到当前坐标的子矩阵内所有数值之和。 通过这种方式,在后续查询任意指定区域内的元素累积值时只需常数时间复杂度 O(1),因为只需要访问四个预处理过的节点即可完成加减运算得出结果[^1]。 #### 应用场景分析 当涉及到像地图服务这样的应用场景时——特别是采用分层切片机制的地图系统(如微软 Bing 地图),这种技术能够显著提升性能效率: - **加速渲染过程**:利用二维前缀和可以在瞬间获取特定范围内的数据汇总信息,从而加快图像合成速度; - **简化碰撞检测逻辑**:游戏开发等领域经常需要用到对象间相互作用判断,借助此方法可迅速定位目标区间并作出响应; - **优化路径规划算法**:无论是最短路还是其他形式的空间搜索问题,都能受益于高效的数据检索能力所带来的优势[^2]。 #### 实现案例展示 下面给出一段 Python 代码片段作为例子说明如何基于上述理论框架构建实际解决方案: ```python def build_prefix_sum(matrix): rows = len(matrix) cols = len(matrix[0]) if matrix else 0 prefix_sum = [[0]*(cols+1) for _ in range(rows+1)] for i in range(1,rows+1): for j in range(1,cols+1): prefix_sum[i][j]=matrix[i-1][j-1]+\ prefix_sum[i-1][j]+ \ prefix_sum[i][j-1]- \ prefix_sum[i-1][j-1] return prefix_sum def query_submatrix_sum(prefix_sum,x1,y1,x2,y2): """Query sum of elements within sub-matrix defined by top-left (x1,y1), bottom-right(x2,y2).""" return prefix_sum[x2+1][y2+1]-prefix_sum[x1][y2+1]-prefix_sum[x2+1][y1]+prefix_sum[x1][y1] # Example usage: input_matrix=[[3,0,1,4],[2,8,7,5],[4,6,9,1]] ps=build_prefix_sum(input_matrix) print(query_submatrix_sum(ps,1,1,2,2)) # Output should be 30 which is the sum inside this area. ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值