构建TensorFlow Dataset时tf.int32类型被误识别为tf.string是什么原因
问题根源
你遇到的类型识别错误核心原因是:
- Pandas中
input_ids、attention_mask列的dtype是object,每个元素是Python原生列表,直接传入tf.convert_to_tensor时,TensorFlow无法直接将包含嵌套列表的object类型结构识别为数值张量,会默认将每个列表序列化为字符串类型,因此出现tf.string的错误类型。 - 若你的序列长度不统一,TensorFlow也无法生成固定维度的数值张量,同样会触发默认的字符串序列化逻辑。
修复方案
场景1:所有序列已经做了padding,长度统一
先将嵌套列表转换为指定int32类型的numpy数组,再传入数据集构建逻辑即可:
import numpy as np # 转换为int32类型的二维numpy数组 train_input_ids = np.array(train_df["input_ids"].tolist(), dtype=np.int32) train_attention_mask = np.array(train_df["attention_mask"].tolist(), dtype=np.int32) # 数据集构建可简化,from_tensor_slices会自动适配张量类型 train_dataset = ( tf.data.Dataset .from_tensor_slices(((train_input_ids, train_attention_mask), y_train)) .repeat() .shuffle(2048) .batch(BATCH_SIZE) .prefetch(BATCH_SIZE * 2) )
场景2:序列为变长、未做padding
使用TensorFlow的不规则张量(RaggedTensor)存储变长序列,显式指定数值类型:
# 构建int32类型的不规则张量 train_input_ids = tf.ragged.constant(train_df["input_ids"].tolist(), dtype=tf.int32) train_attention_mask = tf.ragged.constant(train_df["attention_mask"].tolist(), dtype=tf.int32) # 构建数据集时如果需要批量处理,可后续调用.to_tensor()方法做动态padding train_dataset = ( tf.data.Dataset .from_tensor_slices(((train_input_ids, train_attention_mask), y_train)) .repeat() .shuffle(2048) .batch(BATCH_SIZE) # 动态padding到当前批次的最大长度 .map(lambda x, y: ((x[0].to_tensor(), x[1].to_tensor()), y)) .prefetch(BATCH_SIZE * 2) )
修改后再打印数据集属性,就能看到输入列的类型已经变为tf.int32,符合模型输入要求。
内容的提问来源于stack exchange,提问作者clanofsol
相关产品推荐
相关产品推荐

