首页 > 解决方案 > 如何添加我的 NN 可以预测的每个分类的特定数字?

问题描述

我有一个 np 数组,类似于 0-1 的单热编码。对于每个样本,我总是有 15 个 0 和 5 个 1。我该怎么做才能让它只预测 5 个 1 和 15 个 0?我正在使用 keras 库是否有可以应用的设置,以便我的模型必须准确预测 15 个零和 5 个零?

-

输入示例 = [0 0 0 1 0 1 0 0 1 0 0 1 0 0 0 1 0 0 0 0]

#Building RNN
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout

regressor = Sequential()

regressor.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1],20)))
regressor.add(Dropout(0.2))

regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.2))

regressor.add(LSTM(units = 50, return_sequences = True))

regressor.add(LSTM(units = 50))
regressor.add(Dropout(0.2))

regressor.add(Dense(units = 20, activation='sigmoid'))

# Compiling RNN
regressor.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

我希望我的模型总是预测 15 个零和 5 个。

标签: machine-learningkerasclassificationlstmmultilabel-classification

解决方案


您也可以尝试定义根据您的格式返回的自定义损失函数

def custom_loss(y_true, y_pred):

  # calculate binary_crossentropy and reshape the result according your need
  ...

  return K.variable(...)
regressor.compile(loss=custom_loss, optimizer='adam', metrics=['accuracy'])


推荐阅读