keras-team/keras · error · TypeError

Column weight_col={weight_col} must be numeric.

Error message

Column weight_col={weight_col} must be numeric.

What it means

When weight_col is given to flow_from_dataframe, that DataFrame column must have a numeric dtype so per-sample weights can be used directly.

Source

Thrown at keras/src/legacy/preprocessing/image.py:860

                    "values must be type string, list or tuple.".format(
                        self.class_mode, y_col
                    )
                )
        # raise warning if classes are given but will be unused
        if classes and self.class_mode in {
            "input",
            "multi_output",
            "raw",
            None,
        }:
            warnings.warn(
                '`classes` will be ignored given the class_mode="{}"'.format(
                    self.class_mode
                )
            )
        # check that if weight column that the values are numerical
        if weight_col and not issubclass(df[weight_col].dtype.type, np.number):
            raise TypeError(f"Column weight_col={weight_col} must be numeric.")

    def get_classes(self, df, y_col):
        labels = []
        for label in df[y_col]:
            if isinstance(label, (list, tuple)):
                labels.append([self.class_indices[lbl] for lbl in label])
            else:
                labels.append(self.class_indices[label])
        return labels

    @staticmethod
    def _filter_classes(df, y_col, classes):
        df = df.copy()

        def remove_classes(labels, classes):
            if isinstance(labels, (list, tuple)):
                labels = [cls for cls in labels if cls in classes]
                return labels or None

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Convert: df[weight_col] = pd.to_numeric(df[weight_col], errors='raise')
  2. Re-export the CSV with numeric weights
  3. Fill/drop NaNs before conversion

Example fix

// before
df['w'] = df['w']  # object dtype strings
// after
df['w'] = pd.to_numeric(df['w'])
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np
assert np.issubdtype(df[weight_col].dtype, np.number), df[weight_col].dtype

Type guard

def is_numeric_col(s): return np.issubdtype(s.dtype, np.number)

Try / catch

try: flow_from_dataframe(..., weight_col=w)
except TypeError as e: if 'must be numeric' in str(e): df[w] = pd.to_numeric(df[w])

Prevention

When it happens

Trigger: flow_from_dataframe(..., weight_col='w') where df['w'] is object/string dtype.

Common situations: CSV import storing weights as strings; column with mixed types inferred as object.

Related errors


AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25). Data as JSON: /api/errors/6871ff8458d71923. Report an issue: GitHub.