keras - keras to_categorical 增加了额外的价值
问题描述
我有 4 个需要预测的类,我正在使用 keras'to_categorical
来实现这一点,我希望得到一个 4 个one-hot-encoded
数组,但似乎我得到了 5 个值,[0]
所有行都会出现一个附加值
dict = {'word': 1, 'feature_name': 2, 'feature_value': 3, 'part_number': 4}
Y = dataset['class'].apply(lambda label: dict[label])
print(Y.unique()) #prints [1 4 2 3]
train_x, test_x, train_y, test_y = model_selection.train_test_split(X, Y, test_size=0.2, random_state=0)
train_y = to_categorical(train_y)
print(train_y[0])# prints [0. 0. 1. 0. 0.]
我试图建立的模型如下
model = Sequential()
model.add(Dense(10, input_dim=input_dim, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(4, activation='softmax'))
但它一直在抛出
ValueError: Error when checking target: expected dense_5 to have shape (4,) but got array with shape (5,)
解决方案
您需要从 0 开始对类进行编号,如下所示:
dict = {'word': 0, 'feature_name': 1, 'feature_value': 2, 'part_number': 3}
您可以使用 help() 命令获取函数的描述
help(np_utils.to_categorical)
:
Help on function to_categorical in module keras.utils.np_utils:
to_categorical(y, num_classes=None, dtype='float32')
Converts a class vector (integers) to binary class matrix.
E.g. for use with categorical_crossentropy.
# Arguments
y: class vector to be converted into a matrix
(integers from 0 to num_classes).
num_classes: total number of classes.
dtype: The data type expected by the input, as a string
(`float32`, `float64`, `int32`...)
# Returns
A binary matrix representation of the input. The classes axis
is placed last.
推荐阅读
- javascript - 如何在 JavaScript 中对二维数组进行排序?
- python - 过滤numpy数组但保留原始值
- python - 如何删除许多具有小写名称的变量,Python 3.7.2?
- javascript - 如何将 JS 数据转换为 HTML?
- python - 如何将 unicode 转换为 Python 字符串中的重音字符
- linux - 源脚本与执行脚本:它们在哪个 shell 进程中运行?
- r - 按r中的数字序列分组
- c# - .NET Core CLI 命令无法在 Windows 10 上创建新应用
- entity-framework - 如何从 EF 对象上下文中获取联结表名称和键?
- python - 当主进程终止时,由 Celery 启动的进程不会停止