天天看點

序列預處理:序列填充之pad_sequences()和one-hot轉化之keras.utils.to_categorical()

tensorflow文本進行中,經常會将 padding 和 one-hot 操作共同出現,是以以下兩種方法為有效且常用的方法:

一、keras.preprocessing.sequence.pad_sequences()

序列預處理:序列填充之pad_sequences()和one-hot轉化之keras.utils.to_categorical()

執行個體:

>>>list_1 = [[2,3,4]]
>>>keras.preprocessing.sequence.pad_sequences(list_1, maxlen=10)
array([[0, 0, 0, 0, 0, 0, 0, 2, 3, 4]], dtype=int32)

>>>list_2 = [[1,2,3,4,5]]
>>>keras.preprocessing.sequence.pad_sequences(list_2, maxlen=10)
array([[0, 0, 0, 0, 0, 1, 2, 3, 4, 5]], dtype=int32)

           

二、keras.utils.to_categorical()

to_categorical(y, num_classes=None, dtype='float32')
           

将整型标簽轉為onehot。y為int數組,num_classes為标簽類别總數,大于max(y)(标簽從0開始的)。

傳回:如果num_classes=None,傳回len(y) * [max(y)+1](次元,m*n表示m行n列矩陣,下同),否則為len(y) * num_classes。說出來顯得複雜,請看下面執行個體。

import keras

ohl=keras.utils.to_categorical([1,3])
# ohl=keras.utils.to_categorical([[1],[3]])
print(ohl)
"""
[[0. 1. 0. 0.]
 [0. 0. 0. 1.]]
"""
ohl=keras.utils.to_categorical([1,3],num_classes=5)
print(ohl)
"""
[[0. 1. 0. 0. 0.]
 [0. 0. 0. 1. 0.]]
"""

           

繼續閱讀