Source code for deepctr.estimator.utils

import tensorflow as tf
from tensorflow.python.estimator.canned.head import _Head
from tensorflow.python.estimator.canned.optimizers import get_optimizer_instance

LINEAR_SCOPE_NAME = 'linear'
DNN_SCOPE_NAME = 'dnn'


def _summary_key(head_name, val):
    return '%s/%s' % (val, head_name) if head_name else val





[docs]def deepctr_model_fn(features, mode, logits, labels, task, linear_optimizer, dnn_optimizer, training_chief_hooks): linear_optimizer = get_optimizer_instance(linear_optimizer, 0.005) dnn_optimizer = get_optimizer_instance(dnn_optimizer, 0.01) train_op_fn = get_train_op_fn(linear_optimizer, dnn_optimizer) head = Head(task) return head.create_estimator_spec(features=features, mode=mode, labels=labels, train_op_fn=train_op_fn, logits=logits, training_chief_hooks=training_chief_hooks)
[docs]def get_train_op_fn(linear_optimizer, dnn_optimizer): def _train_op_fn(loss): train_ops = [] try: global_step = tf.train.get_global_step() except AttributeError: global_step = tf.compat.v1.train.get_global_step() linear_var_list = get_collection(get_GraphKeys().TRAINABLE_VARIABLES, LINEAR_SCOPE_NAME) dnn_var_list = get_collection(get_GraphKeys().TRAINABLE_VARIABLES, DNN_SCOPE_NAME) if len(dnn_var_list) > 0: train_ops.append( dnn_optimizer.minimize( loss, var_list=dnn_var_list)) if len(linear_var_list) > 0: train_ops.append( linear_optimizer.minimize( loss, var_list=linear_var_list)) train_op = tf.group(*train_ops) with tf.control_dependencies([train_op]): try: return tf.assign_add(global_step, 1).op except AttributeError: return tf.compat.v1.assign_add(global_step, 1).op return _train_op_fn
[docs]def variable_scope(name_or_scope): try: return tf.variable_scope(name_or_scope) except AttributeError: return tf.compat.v1.variable_scope(name_or_scope)
[docs]def get_collection(key, scope=None): try: return tf.get_collection(key, scope=scope) except AttributeError: return tf.compat.v1.get_collection(key, scope=scope)
[docs]def get_GraphKeys(): try: return tf.GraphKeys except AttributeError: return tf.compat.v1.GraphKeys
[docs]def get_losses(): try: return tf.compat.v1.losses except AttributeError: return tf.losses
[docs]def input_layer(features, feature_columns): try: return tf.feature_column.input_layer(features, feature_columns) except AttributeError: return tf.compat.v1.feature_column.input_layer(features, feature_columns)
[docs]def get_metrics(): try: return tf.compat.v1.metrics except AttributeError: return tf.metrics
[docs]def to_float(x, name="ToFloat"): try: return tf.to_float(x, name) except AttributeError: return tf.compat.v1.to_float(x, name)
[docs]def summary_scalar(name, data): try: tf.summary.scalar(name, data) except AttributeError: # tf version 2.5.0+:AttributeError: module 'tensorflow._api.v2.summary' has no attribute 'scalar' tf.compat.v1.summary.scalar(name, data)