在 TensorFlow 数据管道中使用不规则张量时出现类型错误

问题描述 投票:0回答:1

我尝试在 TensorFlow 中使用

tf.data
创建一个
RaggedTensors
管道,但我不断遇到 TypeError:

"Cannot convert the argument `type_value`: RaggedTensorSpec(TensorShape(\[None, 3\]), tf.int16, 1, tf.int64) to a TensorFlow DType."

我在下面提供了我的代码供参考:

def data_generator():
    for label, file in enumerate(['a.npy', 'b.npy']):
        yield generate_sample(file), label

def generate_sample(file_path):
    sequence = load_npy_file(file_path)
    return tf.cast(tf.ragged.constant(generate_windows(sequence)), dtype=tf.int16)

def load_npy_file(file_path):
    data = np.load(file_path, allow_pickle=True)
    return data.astype(np.int16)

def generate_windows(sequence):
    windows = [sequence[i:i + 2] for i in range(len(sequence) - 2 + 1)]
    return np.array(windows, dtype=np.int16)

np.save('a.npy', np.array([1,2,3,4], dtype=np.int16))
np.save('b.npy', np.array([5,6,7,8,9], dtype=np.int16))
output_signature = (
        tf.RaggedTensorSpec(shape=(None, 2), dtype=tf.int16),
        tf.TensorSpec(shape=(), dtype=tf.int32)
)
dataset = tf.data.Dataset.from_generator(data_generator, output_signature)

检查生成的 RaggedTensors 的形状后,我注意到它们与

output_signature
中定义的形状不同:
RaggedTensorSpec(TensorShape([3, None]), tf.int16, 1, tf.int32)
RaggedTensorSpec(TensorShape([4, None]), tf.int16, 1, tf.int32)
。这种差异会导致错误吗?我将非常感谢任何解决此问题的见解或解决方案。谢谢!

python tensorflow pipeline tensorflow-datasets
1个回答
0
投票

最后一行对

from_generator()
的调用似乎存在参数不匹配。从我的角度来看,这解决了问题:

dataset = tf.data.Dataset.from_generator(data_generator, output_signature=output_signature)

请参阅该函数的 docs。第二个参数是

output_types
,不是签名。

© www.soinside.com 2019 - 2024. All rights reserved.