【pytorch】關於Embedding和GRU、LSTM的使用詳解
原文章:https://www.cnblogs.com/duye/p/10590146.html
文章中在變換句子矩陣的時候使用了itertools模塊的zip_longest函數。使用方法如下:
batch = list(itertools.zip_longest(batch,fillvalue=PAD))
# fillvalue就是要填充的值,強制轉成list
這個函數一般的使用方法爲:
res = zip_longest('abc', '12')
for x in res:
print(x)
#('a', '1')
#('b', '2')
#('c', None)
但是batch是一個嵌套list,如果按照上面的用法,列爲:
res = zip_longest(batch[0],batch[1],batch[2]...)
不合理,因爲不知道batch的長度,而且這樣遍歷有點不方便。網上找不到合適的解決方案,於是我開始嘗試,利用了指針的思想,真的試出來了!答案就是在batch前面加一個 * ,如下:
res = zip_longest(*batch)
歡迎留言