我正在尝试将一个单一的整数向量数组生成一个单热矢量数组,keras将能够使用它来拟合我的模型.这是代码的相关部分:
Y_train = np.hstack(np.asarray(dataframe.output_vector)).reshape(len(dataframe),len(output_cols))
dummy_y = np_utils.to_categorical(Y_train)
Run Code Online (Sandbox Code Playgroud)
下面是显示实际内容Y_train和dummy_y实际内容的图像.

我找不到任何文件to_categorical可以帮助我.
提前致谢.
Ami*_*aha 28
np.utils.to_categorical 用于将标记数据的数组(从0到nb_classes-1)转换为单热矢量.
官方文档的一个例子.
In [1]: from keras.utils import np_utils # from keras import utils as np_utils
Using Theano backend.
In [2]: np_utils.to_categorical?
Signature: np_utils.to_categorical(y, num_classes=None)
Docstring:
Convert class vector (integers from 0 to nb_classes) to binary class matrix, for use with categorical_crossentropy.
# Arguments
y: class vector to be converted into a matrix
nb_classes: total number of classes
# Returns
A binary matrix representation of the input.
File: /usr/local/lib/python3.5/dist-packages/keras/utils/np_utils.py
Type: function
In [3]: y_train = [1, 0, 3, 4, 5, 0, 2, 1]
In [4]: """ Assuming the labeled dataset has total six classes (0 to 5), y_train is the true label array """
In [5]: np_utils.to_categorical(y_train, num_classes=6)
Out[5]:
array([[ 0., 1., 0., 0., 0., 0.],
[ 1., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 1., 0., 0.],
[ 0., 0., 0., 0., 1., 0.],
[ 0., 0., 0., 0., 0., 1.],
[ 1., 0., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0., 0.],
[ 0., 1., 0., 0., 0., 0.]])
Run Code Online (Sandbox Code Playgroud)
from keras.utils.np_utils import to_categorical
Run Code Online (Sandbox Code Playgroud)
更新 ---keras.utils.np_utils在较新版本中不起作用;如果是这样,请使用:
from tensorflow.keras.utils import to_categorical
Run Code Online (Sandbox Code Playgroud)
在这两种情况下
to_categorical(0, max_value_of_array)
Run Code Online (Sandbox Code Playgroud)
它假设类值在字符串中,并且您将对它们进行标签编码,因此每次从 0 到 n 类开始。
for the same example:- consider an array of {1,2,3,4,2}
The output will be [zero value, one value, two value, three value, four value]
array([[ 0., 1., 0., 0., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 0., 0., 1., 0.],
[ 0., 0., 0., 0., 1.],
[ 0., 0., 1., 0., 0.]],
Run Code Online (Sandbox Code Playgroud)
让我们再看一个例子:-
Again, for an array having 3 classes, Y = {4, 8, 9, 4, 9}
to_categorical(Y) will output
array([[0., 0., 0., 0., 1., 0., 0., 0., 0., 0. ],
[0., 0., 0., 0., 0., 0., 0., 0., 1., 0. ],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 1. ],
[0., 0., 0., 0., 1., 0., 0., 0., 0., 0. ],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 1. ]]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48096 次 |
| 最近记录: |