example 排序 batch中按句子長度排序

2021-10-18 10:59:31 字數 3242 閱讀 6608

使用nn.utils.rnn.pack_padded_sequence和nn.utils.rnn.pad_packed_sequence之前,需要對batch中的資料進行從長到短的排序,排序後才能使用:

排序過程**如下(來自**的源**):

def sort_all(batch, lens):

""" sort all fields by descending order of lens, and return the original indices. """

unsorted_all = [lens] + [range(len(lens))] + (batch)

sorted_all = [list(t) for t in zip(*sorted(zip(*unsorted_all), reverse=true))]

return sorted_all[2:], sorted_all[1]# sorted_all記錄每條example在原來的位置

雖然只有短短幾行,我卻看得極為艱難,為了防止後續忘記,下面給出分解過程:

def sort_all(batch, lens):

""" sort all fields by descending order of lens, and return the original indices. """

# unsorted_all = [lens] + [range(len(lens))] + (batch)

# sorted_all = [list(t) for t in zip(*sorted(zip(*unsorted_all), reverse=true))]

# return sorted_all[2:], sorted_all[1]# sorted_all記錄每條example在原來的位置

unsorted_all = [lens] + [range(len(lens))] + (batch)

aa = zip(*unsorted_all)

bb = sorted(aa, reverse=true)

cc = zip(*bb)

sorted_all = [list(t) for t in cc]

return sorted_all[2:], sorted_all[1]

if __name__ == "__main__":

## 三個句子

sent_set = list()

sent1 = ["sent1_w1", "sent1_w2", "sent1_w3", "sent1_w4"]

sent2 = ["sent2_w1", "sent2_w2", "sent2_w3"]

sent3 = ["sent3_w1", "sent3_w2", "sent3_w3", "sent3_w4", "sent3_w5"]

## 三個句子每個詞對應的詞性特徵

pos_set = list()

pos1 = ["sent1_p1", "sent1_p2", "sent1_p3", "sent1_p4"]

pos2 = ["sent2_p1", "sent2_p2", "sent2_p3"]

pos3 = ["sent3_p1", "sent3_p2", "sent3_p3", "sent3_p4", "sent3_p5"]

batch = list()

lens = [4, 3, 5]

origin_index, _ = sort_all(batch, lens)

print(origin_index)

結合例子講解**:

引數batch:可以由例子清晰看出batch的結構

引數lens:句子長度的列表,句子長度分別是[4, 3, 5]

執行**:

第0個元素是[4, 3, 5] 對應三個句子的句長

第1個元素range(0, 3) 是乙個物件,

第2個元素是batch中句子集合

第3個元素是batch中詞性特徵集合

2. 執行**:

aa = zip(*unsorted_all)

for elem in aa :

print(elem)

這裡需要了解zip()函式的用法

這個zip 可不是window中壓縮包字尾名哦

可以這麼形象地理解

第一行: 4 3 5

第二行: 0 1 2

第三行:sent1_seq sent2_seq sent3_seq

第四行:pos1_seq pos2_seq pos3_seq

可以將上面看成是乙個四行三列的矩陣,zip的功能可以理解為按列劃分,

3. 執行**:

bb = sorted(aa, reverse=true)
bb的結果是:

reverse=true, 按照從大到小的順序進行排序

4.執行**:

cc = zip(*bb)

for c in cc:

print(c)

執行結果如下:

5. 執行**:

sorted_all = [list(t) for t in cc]
此時已經完成了排序:

第0個元素[5, 4, 3]是排序後各句子的長度

第1個元素[2, 0, 1]是未排序時在batch中的下標

SpringBoot中Example的動態條件查詢

一 無匹配器的情況 person person new person person.setname test role role new role role.setname 經理 person.setrole role example ex example.of person 動態查詢 person...

Mybatis中example類的使用

給出例項 是實體類 查詢操作 現在使用example查詢 example example new example country.class example.createcriteria andequalto id 100 這裡給出查詢為id 100 example.setorderbyclause...

mybatis中關於example類詳解

這幾天剛接觸example,很多內容都是破碎的,寫一篇博文加深理解。一 什麼是example類 mybatis generator會為每個字段產生如上的criterion,如果表的字段比較多,產生的example類會十分龐大。理論上通過example類可以構造你想到的任何篩選條件。在mybatis ...