我的一位同事指出,当您需要在 Keras 中屏蔽非 RNN 的输入时,使用 sample_weight 而不是屏蔽层是一个非常酷的选择。
在我的例子中,输入中有 62 列,第 63 列是响应。 62 列中超过 97% 的非零条目包含在前 30 列中。我正在尝试让它工作,所以我想在训练中将最后 32 列的权重设置为 0,本质上是创建一个“穷人的面具”。
这是一个 8 类分类任务,使用 MLP。已使用 Keras 中的 to_categorical() 函数转换响应变量。
实现如下:
model = Sequential()
model.add(Dense(100, input_dim=X.shape[1], init='uniform', activation='relu'))
model.add(Dense(8, init='uniform', activation='sigmoid'))
hist = model.fit(X, y,
validation_data=(X_test, ytest),
nb_epoch=epochs_,
batch_size=batch_size_,
callbacks=callbacks_list,
sample_weight = np.array([X.shape[1]-32, 30]))
我收到这个错误:
in standardize_weights
assert y.shape[:sample_weight.ndim] == sample_weight.shape
如何修复我的 sample_weight 以“屏蔽”输入的前 32 列?
请您参考如下方法:
样本权重不是这样工作的:
sample_weight: optional array of the same length asx, containing weights to apply to the model's loss for each sample. In the case of temporal data, you can pass a 2D array with shape(samples, sequence_length), to apply a different weight to every timestep of every sample. In this case you should make sure to specifysample_weight_mode="temporal"incompile(). source
换句话说,此设置对训练数据的样本赋予不同的权重,而不是对每个样本的特征赋予不同的权重。这仅在训练步骤中使用。 如果您不希望图层使用这些功能,我认为您应该使用 mask 。或者只是将它们从您的数据集中删除?或者,如果不是太复杂,让网络自己学习哪些有用的特征。
这有帮助吗?
