【问题标题】:Tensorflow Estimator API embedding_column compute neighbourhoodTensorflow Estimator API embedding_column 计算邻域
【发布时间】:2018-03-20 12:03:42
【问题描述】:

我正在尝试使用最新的估算器 API 在 tensorflow 中实现与 word2vec 类似的模型。 我遇到的问题是当我尝试评估模型时。模型本身应该是推荐系统的基础。现在我要使用的评估指标是 Hitrate 指标,如下:

  • 为每个输入计算 k 邻域。
  • 确定预期标签是否在 k 邻域中,如果是,则推荐成功。

现在我已经设置了这样的模型:

# Map Embeddings Ids to One Hot Tensors
ref_embedding_ids = tf.feature_column.categorical_column_with_identity(
    key='Reference',
    num_buckets=params['dict_size'],
    default_value=0
)

# Map One Hot Tensors to Dense Embeddings
ref_embeddings = tf.feature_column.embedding_column(
    ref_embedding_ids,
    dimension=params['embedding_size']
)
# Actually create the input to the model
input_layer = tf.feature_column.input_layer(features, feature_columns=[ref_embeddings])

正如在估算器 API 教程中所做的那样。现在,当我理解这段代码时,input_layer 已经只包含在特征字典中使用键 Reference 引用的嵌入。这太棒了,因为我们不需要将所有嵌入都保存在内存中。 但是现在如果我想在评估模式下计算邻域,我需要访问所有可能输入的嵌入向量来计算相似度。但是我对这些没有任何参考,因为管道设置为只加载必要的部分。我已经尝试找出包含嵌入的变量的名称并使用tf.get_variable 显式加载它,但这也不起作用。 所以我的问题是如何计算给定嵌入 id 的邻域?

此外,在能够计算邻域之后,我需要使用一个度量来继续计算整个评估集的度量,因为该函数会为来自数据集的每个批次调用。但我想这是一个不同的问题,我只是在上下文中提及它。

【问题讨论】:

  • 您能找到解决方案吗?我正在尝试做同样的事情,但无法找到访问嵌入向量以在其上运行最近邻算法的方法

标签: python tensorflow word2vec tensorflow-estimator


【解决方案1】:

我能够通过将cols_to_vars 参数用于tf.feature_column.input_layer 函数来实现此功能。 基本上你需要将一个空字典传递给 tf.feature_column.input_layer ,它将填充输入层中生成的变量。 下面的示例仅包含 model_fn 函数的模型范围。希望有帮助。

def my_model_fn(features, labels, mode, params):

  with tf.name_scope('model'):
    num_vocabulary = len(params['vocabulary'])

    #create embedding vectors for history feature
    vocabulary_lookup = tf.contrib.lookup.index_table_from_tensor(
      name='vocabulary_lookup',
      mapping=params['vocabulary'],
      default_value=-1,
      num_oov_buckets=1
    )
    #print("lookup: {}".format(vocabulary_lookup))

    #create a bais matrix
    rank_biases = tf.get_variable(name='rank_biases', shape=[num_vocabulary])

    # input layer
    input_variable_ref = {}
    net = tf.feature_column.input_layer(features, params['feature_columns'], cols_to_vars=input_variable_ref)
    embedding_metrix = input_variable_ref[params['feature_columns'][0]][0]
    print("embedding metrix => {}".format(embedding_metrix))

    # hidden layers
    for units in params['hidden_units']:
      net = tf.layers.dense(net, units=units, activation=tf.nn.relu)

    # output layer
    with tf.name_scope('DNN_output'):
      logits = tf.layers.dense(net, params['out_layer_dim'], activation=None)
      #print("logits shape: {}".format(logits.shape))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 2018-08-19
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多