You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow数据管道加载多目录.npy文件及TypeError报错解决

解决tf.data加载numpy数组时的TypeError问题

你遇到的TypeError: expected str, bytes or os.PathLike object, not Tensor,核心原因是tf.data的map函数在图模式下传递的是Tensor对象,而np.load需要的是字符串/路径类型。直接调用.numpy()或者.as_string()在普通map函数里行不通,因为图模式下不允许直接执行eager模式的操作,得用tf.py_function来桥接numpy和TensorFlow的操作。

下面是修正后的完整代码,我会一步步解释关键改动:

1. 修正数据集创建方式

首先,from_tensor_slices要传入元组而不是列表,这样每个数据元素会是(特征文件路径, 标签文件路径)的配对,方便后续map函数正确接收两个参数:

def load_dataset(text_files, tag_files):
    # 用元组传入,确保每个元素是(text_path, tag_path)的配对
    dataset = tf.data.Dataset.from_tensor_slices((text_files, tag_files))
    # 用tf.py_function包装加载逻辑,允许执行numpy操作
    dataset = dataset.map(
        lambda text_path, tag_path: tf.py_function(
            func=load_files,
            inp=[text_path, tag_path],
            Tout=[tf.float32, tf.float32]  # 根据你的数据类型调整,比如标签是int就用tf.int32
        ),
        num_parallel_calls=AUTO
    )
    # 明确指定张量形状,避免后续batch/模型输入出错
    dataset = dataset.map(lambda x, y: (
        tf.ensure_shape(x, (None, 1, 768)),  # 第一个维度是序列长度,可设为固定值比如(100,1,768)
        tf.ensure_shape(y, (1, 768))
    ))
    return dataset

2. 重写加载函数,适配Tensor路径

load_files函数需要先把Tensor路径转换成numpy字符串,再调用np.load,最后转成Tensor返回:

def load_files(text_path_tensor, tag_path_tensor):
    # 将Tensor路径解码为Python字符串
    text_path = text_path_tensor.numpy().decode('utf-8')
    tag_path = tag_path_tensor.numpy().decode('utf-8')
    
    # 加载numpy数组
    arr = np.load(text_path, allow_pickle=True)
    tags = np.load(tag_path, allow_pickle=True)
    
    # 可选:填充到固定尺寸(根据你的需求调整)
    # 比如如果特征的序列长度不固定,要填充到MAX_SEQ_LENGTH:
    # MAX_SEQ_LENGTH = 100
    # if arr.shape[0] < MAX_SEQ_LENGTH:
    #     pad_width = ((0, MAX_SEQ_LENGTH - arr.shape[0]), (0,0), (0,0))
    #     arr = np.pad(arr, pad_width, mode='constant')
    # elif arr.shape[0] > MAX_SEQ_LENGTH:
    #     arr = arr[:MAX_SEQ_LENGTH]
    
    # 转换为TensorFlow张量并返回
    return tf.convert_to_tensor(arr, dtype=tf.float32), tf.convert_to_tensor(tags, dtype=tf.float32)

3. 其他小修正

  • 你代码里的import pandas as pdb是笔误,应该改成import pandas as pd(如果需要用pandas的话);
  • load_files原来的参数引用错误(用了filename[0]/filename[1]),现在改成直接用传入的两个路径参数;
  • tf.ensure_shape是关键:因为tf.py_function返回的张量形状是未知的,明确形状后,后续的batch操作和模型输入才能正常工作。

这样修改后,你就能正确加载(x,1,768)的特征数组和(1,768)的标签到tf.data中,而且可以正常进行batch、prefetch等操作了。

内容的提问来源于stack exchange,提问作者Azz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 18:03:11