1 to_categorical
- 介绍
将类别向量转换为二进制(只有0和1)的矩阵类型表示。
其表现为将原有的类别向量转换为独热编码(one hot
)的形式。
引入
1
from keras.utils.np_utils import to_categorical
示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17from keras.utils.np_utils import to_categorical
#类别向量定义
a = [0,1,2,3,4,5,6,7,8]
#调用to_categorical将a按照9个类别来进行转换
a = to_categorical(b, 9)
print(a)
执行结果如下:
[[1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 1.]]
2 pad_sequences
- 介绍
将序列转化为经过填充以后的一个长度相同的新序列
1 | keras.preprocessing.sequence.pad_sequences(sequences, |
引入
1
from keras.preprocessing.sequence import pad_sequences
示例
1
2
3
4
5
6
7from keras.preprocessing.sequence import pad_sequences
a = [[2,3,4]]
b = pad_sequences(a, maxlen=10)
print(b)
执行结果如下:
array([[0, 0, 0, 0, 0, 0, 0, 2, 3, 4]], dtype=int32)