TensorFlow数据管道报错:Tensor对象无map属性(Parquet转浮点列表)
问题解决:TensorFlow数据管道处理Parquet字符串数组报错
场景与问题
搭建数据管道从Parquet文件读取数据,将字符串形式的数组转换为浮点列表后输入TensorFlow的fit方法训练(数据量极大,需分批读取)。运行代码时报错:
AttributeError: 'Tensor' object has no attribute 'map'
示例代码
import pandas as pd import numpy as np import tensorflow as tf import tensorflow_io as tfio import json # 原代码遗漏json导入 df1 = pd.DataFrame({'col1':['[1.2, 2.3, 4.5]', '[1.0, 2.2, 4.3]'], 'col2':['[1.2, 0.3, 0.9]', '[1.1, 9.2, 5.3]']}) # 修正原数据格式错误:col1元素缺少逗号 df2 = pd.DataFrame({'col1':['[1.1, 2.1, 4.1]', '[1.09, 2.29, 4.39]'], 'col2':['[12.2, 20.3, 20.96]', '[12.1, 19.2, 15.3]']}) df1.to_parquet("foo.parquet") df2.to_parquet("bar.parquet") columns = { "col1": tf.TensorSpec(tf.TensorShape([]), tf.string), "col2": tf.TensorSpec(tf.TensorShape([]), tf.string), } ds = tf.data.Dataset.list_files("*.parquet") ds = ds.interleave(lambda f: tfio.IODataset.from_parquet(f, columns=columns), cycle_length=2, block_length=2) def decode_json(ip): # 解析字符串数组,固定输出形状(假设每个数组含3个元素) parsed = tf.py_function(lambda x: json.loads(x.numpy().decode()), [ip], Tout=tf.float32) return tf.reshape(parsed, (3,)) def decode(ip): # 单个Tensor直接调用处理函数,而非Dataset的map方法 out1 = decode_json(ip["col1"]) out2 = decode_json(ip["col2"]) return out1, out2 ds = ds.map(decode) # 添加分批操作,适配fit训练需求 ds = ds.batch(2) for elem in ds: print(elem)
错误原因与修正说明
- 核心错误:
ip["col1"]是单个Tensor对象,而非tf.data.Dataset,因此不能调用map方法——map是Dataset专属方法,用于批量处理数据集元素,单个Tensor需直接应用处理函数。 - 额外修正点:
- 补充原代码遗漏的
import json语句; - 修复示例数据中
df2的col1元素格式错误(缺少逗号会导致JSON解析失败); - 对
tf.py_function的返回值做形状固定,确保每个数组长度一致,避免后续训练报错; - 添加
batch操作,将数据分批,符合TensorFlowfit方法的输入要求。
- 补充原代码遗漏的
内容的提问来源于stack exchange,提问作者NikhilKV
相关产品推荐
相关产品推荐

