Using side features: feature preprocessing

简介: One of the great advantages of using a deep learning framework to build recommender models is the freedom to build rich, flexible feature representations.

One of the great advantages of using a deep learning framework to build recommender models is the freedom to build rich, flexible feature representations.

These need to be appropriately transformed in order to be useful in building models:

  • User and item ids have to be translated into embedding vectors: high-dimensional numerical representations that are adjusted during training to help the model predict its objective better.
  • Raw text needs to be tokenized (split into smaller parts such as individual words) and translated into embeddings.
  • Numerical features need to be normalized so that their values lie in a small interval around 0.

The MovieLens dataset

Let's first have a look at what features we can use from the MovieLens dataset:

import pprint

import tensorflow_datasets as tfds

ratings = tfds.load("movielens/100k-ratings", split="train")

for x in ratings.take(1).as_numpy_iterator():
  pprint.pprint(x)

There are a couple of key features here:

  • Movie title is useful as a movie identifier.
  • User id is useful as a user identifier.
  • Timestamps will allow us to model the effect of time.

The first two are categorical features; timestamps are a continuous feature.

Turning categorical features into embeddings

A categorical feature is a feature that does not express a continuous quantity, but rather takes on one of a set of fixed values.

Most deep learning models express these feature by turning them into high-dimensional vectors. During model training, the value of that vector is adjusted to help the model predict its objective better.
For example, suppose that our goal is to predict which user is going to watch which movie. To do that, we represent each user and each movie by an embedding vector. Initially, these embeddings will take on random values - but during training, we will adjust them so that embeddings of users and the movies they watch end up closer together.
Taking raw categorical features and turning them into embeddings is normally a two-step process:

  1. Firstly, we need to translate the raw values into a range of contiguous integers, normally by building a mapping (called a "vocabulary") that maps raw values ("Star Wars") to integers (say, 15)
  2. Secondly, we need to take these integers and turn them into embeddings.

Defining the vocabulary

The first step is to define a vocabulary. We can do this easily using Keras preprocessing layers.

import numpy as np
import tensorflow as tf

movie_title_lookup = tf.keras.layers.experimental.preprocessing.StringLookup()

The layer itself does not have a vocabulary yet, but we can build it using our data.

movie_title_lookup.adapt(ratings.map(lambda x: x["movie_title"]))

print(f"Vocabulary: {movie_title_lookup.get_vocabulary()[:3]}")

Once we have this we can use the layer to translate raw tokens to embedding ids:

movie_title_lookup(["Star Wars (1977)", "One Flew Over the Cuckoo's Nest (1975)"])

Note that the layer's vocabulary includes one (or more!) unknown (or "out of vocabulary", OOV) tokens. This is really handy: it means that the layer can handle categorical values that are not in the vocabulary. In practical terms, this means that the model can continue to learn about and make recommendations even using features that have not been seen during vocabulary construction.

Using feature hashing

We can take this to its logical extreme and rely entirely on feature hashing, with no vocabulary at all. This is implemented in the tf.keras.layers.experimental.preprocessing.Hashing layer.

# We set up a large number of bins to reduce the chance of hash collisions.
num_hashing_bins = 200_000

movie_title_hashing = tf.keras.layers.experimental.preprocessing.Hashing(
    num_bins=num_hashing_bins
)

We can do the lookup as before without the need to build vocabularies:

movie_title_hashing(["Star Wars (1977)", "One Flew Over the Cuckoo's Nest (1975)"])

Defining the embeddings

Now that we have integer ids, we can use the Embedding layer to turn those into embeddings.

An embedding layer has two dimensions: the first dimension tells us how many distinct categories we can embed; the second tells us how large the vector representing each of them can be.

When creating the embedding layer for movie titles, we are going to set the first value to the size of our title vocabulary (or the number of hashing bins). The second is up to us: the larger it is, the higher the capacity of the model, but the slower it is to fit and serve.

movie_title_embedding = tf.keras.layers.Embedding(
    # Let's use the explicit vocabulary lookup.
    input_dim=movie_title_lookup.vocab_size(),
    output_dim=32
)

We can put the two together into a single layer which takes raw text in and yields embeddings.

movie_title_model = tf.keras.Sequential([movie_title_lookup, movie_title_embedding])

Just like that, we can directly get the embeddings for our movie titles:

movie_title_model(["Star Wars (1977)"])

We can do the same with user embeddings:

user_id_lookup = tf.keras.layers.experimental.preprocessing.StringLookup()
user_id_lookup.adapt(ratings.map(lambda x: x["user_id"]))

user_id_embedding = tf.keras.layers.Embedding(user_id_lookup.vocab_size(), 32)

user_id_model = tf.keras.Sequential([user_id_lookup, user_id_embedding])

Normalizing continuous features

Continuous features also need normalization. For example, the timestamp feature is far too large to be used directly in a deep model

for x in ratings.take(3).as_numpy_iterator():
  print(f"Timestamp: {x['timestamp']}.")

We need to process it before we can use it. While there are many ways in which we can do this, discretization and standardization are two common ones.

Standardization

Standardization rescales features to normalize their range by subtracting the feature's mean and dividing by its standard deviation. It is a common preprocessing transformation.

This can be easily accomplished using the tf.keras.layers.experimental.preprocessing.Normalization layer:

timestamp_normalization = tf.keras.layers.experimental.preprocessing.Normalization()
timestamp_normalization.adapt(ratings.map(lambda x: x["timestamp"]).batch(1024))

for x in ratings.take(3).as_numpy_iterator():
  print(f"Normalized timestamp: {timestamp_normalization(x['timestamp'])}.")

Discretization

Another common transformation is to turn a continuous feature into a number of categorical features. This makes good sense if we have reasons to suspect that a feature's effect is non-continuous.
To do this, we first need to establish the boundaries of the buckets we will use for discretization. The easiest way is to identify the minimum and maximum value of the feature, and divide the resulting interval equally:

max_timestamp = ratings.map(lambda x: x["timestamp"]).reduce(
    tf.cast(0, tf.int64), tf.maximum).numpy().max()
min_timestamp = ratings.map(lambda x: x["timestamp"]).reduce(
    np.int64(1e9), tf.minimum).numpy().min()

timestamp_buckets = np.linspace(
    min_timestamp, max_timestamp, num=1000)

print(f"Buckets: {timestamp_buckets[:3]}")

Given the bucket boundaries we can transform timestamps into embeddings:

timestamp_embedding_model = tf.keras.Sequential([
  tf.keras.layers.experimental.preprocessing.Discretization(timestamp_buckets.tolist()),
  tf.keras.layers.Embedding(len(timestamp_buckets) + 1, 32)
])

for timestamp in ratings.take(1).map(lambda x: x["timestamp"]).batch(1).as_numpy_iterator():
  print(f"Timestamp embedding: {timestamp_embedding_model(timestamp)}.")

Processing text features

We may also want to add text features to our model. Usually, things like product descriptions are free form text, and we can hope that our model can learn to use the information they contain to make better recommendations, especially in a cold-start or long tail scenario.
While the MovieLens dataset does not give us rich textual features, we can still use movie titles. This may help us capture the fact that movies with very similar titles are likely to belong to the same series.
The first transformation we need to apply to text is tokenization (splitting into constituent words or word-pieces), followed by vocabulary learning, followed by an embedding.

The Keras tf.keras.layers.experimental.preprocessing.TextVectorization layer can do the first two steps for us:

title_text = tf.keras.layers.experimental.preprocessing.TextVectorization()
title_text.adapt(ratings.map(lambda x: x["movie_title"]))

Let's try it out:

for row in ratings.batch(1).map(lambda x: x["movie_title"]).take(1):
  print(title_text(row))

Each title is translated into a sequence of tokens, one for each piece we've tokenized.

We can check the learned vocabulary to verify that the layer is using the correct tokenization:

title_text.get_vocabulary()[40:45]

This looks correct: the layer is tokenizing titles into individual words.
To finish the processing, we now need to embed the text. Because each title contains multiple words, we will get multiple embeddings for each title. For use in a donwstream model these are usually compressed into a single embedding. Models like RNNs or Transformers are useful here, but averaging all the words' embeddings together is a good starting point.

Putting it all together

With these components in place, we can build a model that does all the preprocessing together.

User model

The full user model may look like the following:

class UserModel(tf.keras.Model):

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

    self.user_embedding = tf.keras.Sequential([
        user_id_lookup,
        tf.keras.layers.Embedding(user_id_lookup.vocab_size(), 32),
    ])
    self.timestamp_embedding = tf.keras.Sequential([
      tf.keras.layers.experimental.preprocessing.Discretization(timestamp_buckets.tolist()),
      tf.keras.layers.Embedding(len(timestamp_buckets) + 2, 32)
    ])
    self.normalized_timestamp = tf.keras.layers.experimental.preprocessing.Normalization()

  def call(self, inputs):

    # Take the input dictionary, pass it through each input layer,
    # and concatenate the result.
    return tf.concat([
        self.user_embedding(inputs["user_id"]),
        self.timestamp_embedding(inputs["timestamp"]),
        self.normalized_timestamp(inputs["timestamp"])
    ], axis=1)

Let's try it out:

user_model = UserModel()

user_model.normalized_timestamp.adapt(
    ratings.map(lambda x: x["timestamp"]).batch(128))

for row in ratings.batch(1).take(1):
  print(f"Computed representations: {user_model(row)[0, :3]}")

Movie model

We can do the same for the movie model:

class MovieModel(tf.keras.Model):

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

    max_tokens = 10_000

    self.title_embedding = tf.keras.Sequential([
      movie_title_lookup,
      tf.keras.layers.Embedding(movie_title_lookup.vocab_size(), 32)
    ])
    self.title_text_embedding = tf.keras.Sequential([
      tf.keras.layers.experimental.preprocessing.TextVectorization(max_tokens=max_tokens),
      tf.keras.layers.Embedding(max_tokens, 32, mask_zero=True),
      # We average the embedding of individual words to get one embedding vector
      # per title.
      tf.keras.layers.GlobalAveragePooling1D(),
    ])

  def call(self, inputs):
    return tf.concat([
        self.title_embedding(inputs["movie_title"]),
        self.title_text_embedding(inputs["movie_title"]),
    ], axis=1)

Let's try it out:

movie_model = MovieModel()

movie_model.title_text_embedding.layers[0].adapt(
    ratings.map(lambda x: x["movie_title"]))

for row in ratings.batch(1).take(1):
  print(f"Computed representations: {movie_model(row)[0, :3]}")

代码地址: https://codechina.csdn.net/csdn_codechina/enterprise_technology/-/blob/master/NLP_recommend/Using%20side%20features:%20feature%20preprocessing.ipynb

目录
相关文章
|
14天前
|
数据采集 Web App开发 人工智能
Rust无头浏览器Obscura实战:30MB内存,爬虫与AI Agent轻量替代
本文介绍 Rust 编写的轻量无头浏览器 Obscura(36k star),内存仅约 30MB、启动瞬时,支持 Puppeteer/Playwright 无缝接管及 MCP 协议,专为网页爬虫与 AI Agent 场景优化,Windows 解压即用,实测截图、并发抓取、代理配置全部跑通。
233 1
|
2月前
|
人工智能 JSON Java
【Agent】测评集搭建指南
本文详解Agent测评体系搭建,分为数据集、轨迹与打分三步:数据集定义任务及成功标准;轨迹记录Agent执行全过程;打分器基于结果与环境状态评估。通过Python实现全流程,使用Tool Mock避免真实调用,支持多类型评分(代码/模型/人工),强调可复现性与灵活扩展,适用于回归测试与性能评估。
380 1
|
2月前
|
人工智能 自然语言处理 语音技术
阿里云Token Plan:Credits统一计量,个人版四档、团队版三档席位,多模态与Agent工具一站配齐,超量尊享88折‌
阿里云 Token Plan 是千问 AI 平台推出的大模型订阅服务,以 Credits 统一计量,将文本、图像、语音、视频等多模态模型及联网搜索、代码解释器等工具纳入同一订阅体系。个人版设 Lite、Essential、Standard、Pro 四档,Standard 与 Pro 附赠独立核算的 Harness 权益;团队版按标准、高级、尊享三档席位订阅,支持席位管理与用量分析。两者均可购买加油包补充额度,并叠加超量 88 折、夜间折扣等优惠。其核心价值在于以统一入口降低多工具切换与预算管理成本,用户可按真实负载与团队规模灵活选档。
|
3月前
|
人工智能 安全 IDE
阿里云Qoder CN产品介绍:Qoder CN是什么、适用场景、产品价格及最新活动
本文是阿里云Qoder CN 2026年最新产品活动全解析,这款定位"AI编程搭子"的智能编程工具,主打自主编程、深度集成、安全可控三大核心能力,覆盖从个人开发到企业级协同的全场景需求。活动推出Night Qoder夜间专属折扣,22:00-次日8点指定模型最低2折起,同步上线免费体验版、个人版、Teams版等多档订阅方案,叠加新用户注册赠调用次数等福利,帮助开发者低成本获得端到端智能编程能力。
|
5月前
|
机器学习/深度学习 缓存 算法
大模型超长上下文显存控制:原生注意力缺陷、长文本显存暴涨原理与优化实践.180
本文详解大模型超长上下文(如128K)的原理、瓶颈与优化方案:揭示Transformer自注意力O(N²)显存爆炸根源,提出FlashAttention-2(降为O(N))、INT4量化、分层加载、CPU/GPU动态卸载四大关键技术,使RTX 4090单卡即可稳定运行长文档总结、整本合同分析等高需求任务,大幅降低本地大模型落地门槛。
675 2
|
运维 大数据 数据建模
连载7:阿里巴巴大数据实践:OneData模型实施介绍
如何从具体的需求或项目转换为可实施的解决方案,如何进行需求分析、架构设计、详细模型设计等,则是模型实施过程中讨论的内容。
7164 1
连载7:阿里巴巴大数据实践:OneData模型实施介绍
|
12月前
|
传感器 监控 网络协议
【开源源码】基于 STM32智能温度监控系统 | 一个支持远程监控与告警的嵌入式实践项目
本项目基于STM32与μC/OS实时操作系统,结合LWIP协议栈,实现支持远程监控与告警的智能温度系统。通过多任务协同,完成温度采集、网络通信与阈值告警,支持手机App实时查看与配置。系统具备高实时性、稳定性与扩展性,是RTOS与物联网技术融合的典型嵌入式实践案例,开源可学,适用于工业、智能家居等场景。
【开源源码】基于 STM32智能温度监控系统 | 一个支持远程监控与告警的嵌入式实践项目
|
12月前
|
存储 弹性计算 网络安全
阿里云用户上云流程参考:从账号注册、实名认证到领取和使用优惠券流程指南
不管我们是需要在阿里云平台注册域名还是需要购买云服务器及其他云产品,第一步都首要完成账号注册与实名认证流程,此为后选购各类云产品的必要前提。同时,在购买过程中,部分云服务器及其他云产品支持叠加使用阿里云赠送的各种优惠券,有效降低采购成本。本文将以图文的形式,为大家解析从阿里云账号注册、实名认证以及优惠券领取与使用的完整流程,助力用户以更优价格选购心仪的云产品。
956 11
|
6月前
|
前端开发 JavaScript Linux
那些影响中国开发者的人:从技术启蒙到生态连接
在中文技术圈,阮一峰、Jeff Barr、左耳朵耗子等布道者以文字启蒙;廖雪峰、鸟哥以教程降低入门门槛;池建强、wiwi则通过社区连接开发者。他们未必代码最强,却都坚持“帮后来者少走弯路”,以不同路径践行技术人的真正影响力——让他人因你而走得更远。
806 0
|
6月前
|
存储 弹性计算 Kubernetes
阿里云容器服务Kubernetes版ACK对接使用完全指南
本文系统阐述阿里云容器服务Kubernetes版(ACK)的对接使用全流程。首先解析ACK托管版、专有版与Serverless版的架构差异与选型策略,帮助用户根据业务场景做出合理决策。随后详细讲解通过控制台创建ACK托管集群的完整步骤,涵盖网络规划(Terway与Flannel对比、CIDR配置)、节点池管理等关键环节。在应用部署层面,深入介绍Deployment、StatefulSet等核心工作负载的YAML编排实践,并通过Service与ALB Ingress实现服务暴露与七层负载均衡。存储管理部分系统讲解基于CSI的云盘动态存储卷与NAS静态存储卷的使用方法。安全与权限方面,阐述RAM授