【问题标题】:Difference in padding integer and string in keraskeras中填充整数和字符串的区别
【发布时间】:2023-03-08 20:39:01
【问题描述】:

我正在尝试为 seq2seq 模型填充文本。

from keras_preprocessing.sequence import pad_sequences

x=[["Hello, I'm Bhaskar", "This is Keras"], ["This is an", "experiment"]]
pad_sequences(sequences=x, maxlen=5, dtype='object', padding='pre', value="<PAD>")

我遇到以下错误:

ValueError: `dtype` object is not compatible with `value`'s type: <class 'str'>
You should set `dtype=object` for variable length strings.

但是,当我尝试对整数执行相同操作时,效果很好。

x=[[1, 2, 3], [4, 5, 6]]
pad_sequences(sequences=x, maxlen=5, padding='pre', value=0)

Output:
array([[0, 0, 1, 2, 3],
       [0, 0, 4, 5, 6]], dtype=int32)

我希望得到如下输出:

[["<PAD>", "<PAD>", "<PAD>", "Hello, I'm Bhaskar", "This is Keras"], ["<PAD>", "<PAD>","<PAD>", "This is an", "experiment"]]

【问题讨论】:

  • 你不能直接传递字符串。或许你可以参考stackoverflow.com/questions/46323296/…
  • 对于 seq2seq 模型,您可以先标记句子,然后填充这些整数序列。 Seq2seq 模型无论如何都会接受字符串值。
  • 我正在使用句子编码制作一个 seq2seq。

标签: python keras nlp


【解决方案1】:

按照错误的建议,将dtype 更改为object(不是字符串,而是对象本身),它会为您完成这项工作。

from keras.preprocessing.sequence import pad_sequences

x=[["Hello, I'm Bhaskar", "This is Keras"], ["This is an", "experiment"]]
pad_sequences(sequences=x, maxlen=5, dtype=object, padding='pre', value="<PAD>")

输出

array([['<PAD>', '<PAD>', '<PAD>', "Hello, I'm Bhaskar", 'This is Keras'],
       ['<PAD>', '<PAD>', '<PAD>', 'This is an', 'experiment']],
      dtype=object)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多