在TensorFlow-Recommender模型中添加经度和纬度作为功能

发布于 2025-02-14 02:06:07 字数 2770 浏览 1 评论 0原文

我正在制作推荐系统。对于类似的查询,我想提出类似的建议。

我从此处遵循以下示例: https://www.tensorflow/推荐人/示例/特征?hl = en

用户创建查询。他可以选择地图上所需的位置,这就是为什么查询在其功能中具有经度和纬度的原因。 我想在建议算法的查询模型中添加经度和纬度。

这是查询模型。它已经将令牌化的文本功能(

class QueryModel(tf.keras.Model):
  
  def __init__(self):
    super().__init__()

    max_tokens = 10_000

    self.query_features_vectorizer = tf.keras.layers.TextVectorization(
        max_tokens=max_tokens)

    self.query_features_embedding = tf.keras.Sequential([
      self.query_features_vectorizer,
      tf.keras.layers.Embedding(max_tokens, 64, mask_zero=True),
      tf.keras.layers.GlobalAveragePooling1D(),
    ])

    self.query_features_vectorizer.adapt(query_features)

  def call(self, inputs):
    # Take the input dictionary, pass it through each input layer,
    # and concatenate the result.
    return tf.concat([
        self.query_features_embedding(inputs["query_features"]),
    ], axis=1)

我将查询模型传递到该排名模型中),该排名模型具有对每个查询候选对的评分的任务:

class RatingsModel(tfrs.models.Model):

  def __init__(self):
    super().__init__()

    # query and warehouse models
    self.query_model = tf.keras.Sequential([
      QueryModel(),
      tf.keras.layers.Dense(16)
    ])
    self.candidate_model = tf.keras.Sequential([
      WarehouseModel(),
      tf.keras.layers.Dense(16)
    ])

    # A small model to take in query and warehouse embeddings and predict ratings.
    # We can make this as complicated as we want as long as we output a scalar
    # as our prediction.
    self.rating_model = tf.keras.Sequential([
        tf.keras.layers.Dense(16, activation="linear"),
        tf.keras.layers.Dense(8, activation="tanh"),
        tf.keras.layers.Dense(1, activation="linear"),
    ])

    self.task = tfrs.tasks.Ranking(
      loss=tf.keras.losses.MeanSquaredError(),
      metrics=[tf.keras.metrics.RootMeanSquaredError("RMSE")]
    )

  def call(self, features):
    query_embeddings = self.query_model({
        "query_features": features["query_features"],
    })

    warehouse_embeddings = self.candidate_model({
        "warehouse_id": features["warehouse_id"],
    })

    return (
        self.rating_model(
            tf.concat([query_embeddings, warehouse_embeddings], axis=1)
        ),
    )

  def compute_loss(self, features, training=False):
    labels = features.pop("similarity")
    
    rating_predictions = self(features)

    # We compute the loss for each task.
    rating_loss = self.task(
        labels=labels,
        predictions=rating_predictions,
    )
    return rating_loss

该算法可以预测查询最相关的候选人的评级。

我的问题是:如何考虑经度和纬度,什么是一般方法?

I am making a recommender system. For similar queries I want to give similar recommendations.

I was following the example from here: https://www.tensorflow.org/recommenders/examples/featurization?hl=en

User creates a query. He can choose the desired location on the map that's why query has longitude and latitude in its features.
I want to add longitude and latitude in the Query model for the recommender algorithm.

Here is the Query model. It already takes the tokenized text features:

class QueryModel(tf.keras.Model):
  
  def __init__(self):
    super().__init__()

    max_tokens = 10_000

    self.query_features_vectorizer = tf.keras.layers.TextVectorization(
        max_tokens=max_tokens)

    self.query_features_embedding = tf.keras.Sequential([
      self.query_features_vectorizer,
      tf.keras.layers.Embedding(max_tokens, 64, mask_zero=True),
      tf.keras.layers.GlobalAveragePooling1D(),
    ])

    self.query_features_vectorizer.adapt(query_features)

  def call(self, inputs):
    # Take the input dictionary, pass it through each input layer,
    # and concatenate the result.
    return tf.concat([
        self.query_features_embedding(inputs["query_features"]),
    ], axis=1)

I pass query model into this ranking model that has a task to give ratings to each query-candidate pair:

class RatingsModel(tfrs.models.Model):

  def __init__(self):
    super().__init__()

    # query and warehouse models
    self.query_model = tf.keras.Sequential([
      QueryModel(),
      tf.keras.layers.Dense(16)
    ])
    self.candidate_model = tf.keras.Sequential([
      WarehouseModel(),
      tf.keras.layers.Dense(16)
    ])

    # A small model to take in query and warehouse embeddings and predict ratings.
    # We can make this as complicated as we want as long as we output a scalar
    # as our prediction.
    self.rating_model = tf.keras.Sequential([
        tf.keras.layers.Dense(16, activation="linear"),
        tf.keras.layers.Dense(8, activation="tanh"),
        tf.keras.layers.Dense(1, activation="linear"),
    ])

    self.task = tfrs.tasks.Ranking(
      loss=tf.keras.losses.MeanSquaredError(),
      metrics=[tf.keras.metrics.RootMeanSquaredError("RMSE")]
    )

  def call(self, features):
    query_embeddings = self.query_model({
        "query_features": features["query_features"],
    })

    warehouse_embeddings = self.candidate_model({
        "warehouse_id": features["warehouse_id"],
    })

    return (
        self.rating_model(
            tf.concat([query_embeddings, warehouse_embeddings], axis=1)
        ),
    )

  def compute_loss(self, features, training=False):
    labels = features.pop("similarity")
    
    rating_predictions = self(features)

    # We compute the loss for each task.
    rating_loss = self.task(
        labels=labels,
        predictions=rating_predictions,
    )
    return rating_loss

The algorithm predicts the rating for the most relevant candidates for the query.

My question is: how can I take the longitude and latitude into account, what is the general approach?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

箹锭⒈辈孓 2025-02-21 02:06:07

在此中,Google blog 对如何进行解释建模地理坐标。您可以使用特征十字来结合经度和纬度特征。

In this Google blog an explaination is given on how to model geographic coordinates. You can make use of feature crosses to combine the longitude and latitude features.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文