TensorFlow Recommenders报错:tuple indices must be integers or slices, not str
排查TensorFlow列表式排序推荐系统的TypeError问题
以下是针对tuple indices must be integers or slices, not str报错的常见排查方向及解决方法:
数据集结构不匹配
检查训练数据集是否被处理成了tuple而非字典结构。如果预处理后每个样本是(userId, game_title, rating)这类tuple,模型尝试用字符串键(如"userId")访问时就会触发报错。- 解决:确保数据集样本为字典格式,每个字段对应字符串键:
# 示例:将原始数据转换为字典结构的数据集 dataset = tf.data.Dataset.from_tensor_slices({ "userId": user_id_list, "game_title": game_title_list, "rating": rating_list })
- 解决:确保数据集样本为字典格式,每个字段对应字符串键:
模型输入层与数据键不对应
确认RetailModel的输入层是否指定了正确的name参数,且与数据集的键完全一致。如果输入层未命名或名称不匹配,模型会将输入当作tuple处理,导致索引报错。- 解决:定义输入层时明确指定
name:user_input = tf.keras.Input(shape=(), dtype=tf.string, name="userId") game_input = tf.keras.Input(shape=(), dtype=tf.string, name="game_title") rating_input = tf.keras.Input(shape=(), dtype=tf.int32, name="rating")
- 解决:定义输入层时明确指定
数据管道映射函数错误
检查tf.data管道中的map函数是否返回了tuple而非字典。比如错误地返回(user_id, game_title, rating),而非包含键值对的字典。- 解决:修改映射函数返回字典:
def preprocess_data(user_id, game_title, rating): return { "userId": user_id, "game_title": game_title, "rating": rating } # 假设原始数据集是tuple格式,通过map转换为字典 dataset = dataset.map(preprocess_data)
- 解决:修改映射函数返回字典:
模型拟合时输入格式错误
调用model.fit()时,若传入的x参数是tuple而非字典,模型会无法识别字符串键,触发索引错误。- 解决:将
x参数设为对应输入层名称的字典:model.fit( x={ "userId": train_user_ids, "game_title": train_game_titles, "rating": train_ratings }, epochs=10, batch_size=32 )
- 解决:将
内容的提问来源于stack exchange,提问作者Nicolas Nuñez Manzano
相关产品推荐
相关产品推荐

