Skip to content

Invalid class_weight silently ignored in model.fit(), no error raised #98283

@tinywisdom

Description

@tinywisdom

Issue type

Bug

Have you reproduced the bug with TensorFlow Nightly?

No

Source

source

TensorFlow version

TensorFlow version: 2.19.0

Custom code

Yes

OS platform and distribution

Ubuntu 22.04.4 LTS (x86_64)

Mobile device

Ubuntu 22.04.4 LTS (x86_64)

Python version

3.10.16

Bazel version

bazel 8.3.1

GCC/compiler version

clang-18.1.8

CUDA/cuDNN version

12.5.1/9.3.0

GPU model and memory

NVIDIA RTX A6000 49140MiB

Current behavior?

Passing an invalid class_weight dictionary (with a non-integer key that doesn’t match any class index) into model.fit() does not raise any error or warning. Instead, the training proceeds as if no class_weight was provided, which can lead to silent misbehavior.

This contradicts the expectation that invalid class_weight keys should raise a ValueError or KeyError, as in earlier versions or typical user expectations.

Standalone code to reproduce the issue

import tensorflow as tf
from tensorflow.keras import layers

class MyModel(tf.keras.Model):
    def __init__(self):
        super().__init__()
        self.dense = layers.Dense(4, activation='relu')

    def call(self, inputs):
        return self.dense(inputs)

if __name__ == "__main__":
    import os
    os.environ["CUDA_VISIBLE_DEVICES"] = "3"

    model = MyModel()
    model.compile(optimizer='adam', loss='mse')

    x = tf.random.normal((10, 1))
    y = tf.ones((10, 1))

    try:
        model.fit(x, y, class_weight={'invalid': 0.5}, verbose=0)
        assert False, "BUG_TRIG: Invalid class_weight should raise error"
    except (ValueError, KeyError) as e:
        print("Caught expected error:", e)

Relevant log output

Traceback (most recent call last):
  ...
AssertionError: BUG_TRIG: Invalid class_weight should raise error

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions