Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

training.py _weighted_masked_objective fix crash when weights is None #7068

Merged
merged 2 commits into from
Jun 21, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions keras/engine/training.py
Original file line number Diff line number Diff line change
Expand Up @@ -444,13 +444,12 @@ def weighted(y_true, y_pred, weights, mask=None):
# to the number of unmasked samples.
score_array /= K.mean(mask)

# reduce score_array to same ndim as weight array
ndim = K.ndim(score_array)
weight_ndim = K.ndim(weights)
score_array = K.mean(score_array, axis=list(range(weight_ndim, ndim)))

# apply sample weighting
if weights is not None:
# reduce score_array to same ndim as weight array
ndim = K.ndim(score_array)
weight_ndim = K.ndim(weights)
score_array = K.mean(score_array, axis=list(range(weight_ndim, ndim)))
score_array *= weights
score_array /= K.mean(K.cast(K.not_equal(weights, 0), K.floatx()))
return K.mean(score_array)
Expand Down
16 changes: 15 additions & 1 deletion tests/keras/engine/test_training.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

from keras.layers import Dense, Dropout
from keras.engine.topology import Input
from keras.engine.training import Model, _check_loss_and_target_compatibility
from keras.engine.training import Model
from keras.engine.training import _check_loss_and_target_compatibility
from keras.engine.training import _weighted_masked_objective
from keras.models import Sequential
from keras import backend as K
from keras.utils import Sequence
Expand All @@ -27,6 +29,18 @@ def __getitem__(self, idx):
np.random.random((self.batch_size, 3))]


@keras_test
def test_weighted_masked_objective():
a = Input(shape=(3,), name='input_a')

# weighted_masked_objective
def mask_dummy(y_true=None, y_pred=None, weight=None):
return K.placeholder(y_true.shape)

weighted_function = _weighted_masked_objective(K.categorical_crossentropy)
weighted_function(a, a, None)


@keras_test
def test_model_methods():
a = Input(shape=(3,), name='input_a')
Expand Down