13
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

kerasのpad_sequencesを使うときはdtypeを指定しなければいけない理由

Posted at

kerasのpad_sequencesとは

各ベクトルの長さが揃っていないとき、0をつけたすorカットすることで同じ長さに揃えるためのメソッドです。

例えば・・・

>>> from keras.preprocessing import sequence
>>> import numpy as np
>>> data = [np.array([[1,2,3],[4,5,6]]),
...         np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]])]
>>> data
[array([[1, 2, 3],
       [4, 5, 6]]), array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12],
       [13, 14, 15]])]
>>> #長さを4に揃える。
>>> data = sequence.pad_sequences(data, maxlen=4,padding="post", truncating="post")
>>> data
array([[[ 1,  2,  3],
        [ 4,  5,  6],
        [ 0,  0,  0],
        [ 0,  0,  0]],

       [[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9],
        [10, 11, 12]]], dtype=int32)

dtypeを指定しなければいけない理由

dtypeを指定しない場合、デフォルトではint32の値が返ってきます。

そうすると、もとのdataに浮動小数点があった場合、強制的にint32に変換されてしまいます

例えば0.1は0になってしまいます。

↓dtypeを指定しなかった場合

>>> from keras.preprocessing import sequence
>>> import numpy as np
>>> # float混じりのdata
>>> data = [np.array([[0.1,0.2,0.3],[0.4,0.5,0.6]]),
...         np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]])]
>>> data
[array([[0.1, 0.2, 0.3],
       [0.4, 0.5, 0.6]]), array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12],
       [13, 14, 15]])]
>>> # 長さを4に揃える。
>>> data = sequence.pad_sequences(data, maxlen=4,padding="post", truncating="post")
>>> # floatだった値がint32に自動でcastされ、0になってしまう
>>> data
array([[[ 0,  0,  0],
        [ 0,  0,  0],
        [ 0,  0,  0],
        [ 0,  0,  0]],

       [[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9],
        [10, 11, 12]]], dtype=int32)

結論

pad_sequencesを使うときはdtypeを指定しましょう。

sequence.pad_sequences(data, maxlen=4, padding="post", 
truncating="post", dtype=float32)
13
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?