{"record":{"id":"9a3575b06f40d0d7","repo":"keras-team/keras","slug":"when-setting-values-directly-mean-and-variance","errorCode":null,"errorMessage":"When setting values directly, `mean` and `variance` must have the same shape. Received: mean shape {np.shape(mean)} and variance shape {np.shape(variance)}","messagePattern":"When setting values directly, `mean` and `variance` must have the same shape\\. Received: mean shape (.+?) and variance shape (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"keras/src/layers/preprocessing/normalization.py","lineNumber":140,"sourceCode":"        self.axis = axis\n\n        self.input_mean = mean\n        self.input_variance = variance\n        self.invert = invert\n        self.supports_masking = True\n        self._build_input_shape = None\n        self.mean = None\n\n        # Set `mean` and `variance` if passed.\n        if (mean is not None) != (variance is not None):\n            raise ValueError(\n                \"When setting values directly, both `mean` and `variance` \"\n                f\"must be set. Received: mean={mean} and variance={variance}\"\n            )\n        if mean is not None:\n            # Verify mean and variance have the same shape.\n            if np.shape(mean) != np.shape(variance):\n                raise ValueError(\n                    \"When setting values directly, `mean` and `variance` \"\n                    \"must have the same shape. Received: \"\n                    f\"mean shape {np.shape(mean)} and \"\n                    f\"variance shape {np.shape(variance)}\"\n                )\n            # Verify mean rank <= number of axes.\n            if len(np.shape(mean)) > len(self.axis):\n                raise ValueError(\n                    \"The rank of `mean` must be less than or equal to the \"\n                    f\"number of axes ({len(self.axis)}). Received: \"\n                    f\"mean shape {np.shape(mean)} for axis {self.axis}\"\n                )\n\n    def build(self, input_shape):\n        if input_shape is None:\n            return\n\n        ndim = len(input_shape)","sourceCodeStart":122,"sourceCodeEnd":158,"githubUrl":"https://github.com/keras-team/keras/blob/7a34a03db60bf60042242d6a556fc3be119046a5/keras/src/layers/preprocessing/normalization.py#L122-L158","documentation":"Normalization broadcasts mean and variance across the non-normalized axes, so the two arrays must have identical shapes. __init__ compares np.shape(mean) vs np.shape(variance) and raises on mismatch.","triggerScenarios":"Normalizing axis=-1 with mean of shape (768,) but variance of shape (1,768); statistics exported from different sources or with squeeze/reshape applied inconsistently.","commonSituations":"Loading channel statistics from separate files (mean.npy, std.npy then squaring); mixing per-feature stats computed at different data versions.","solutions":["Reshape both to the same shape, typically via .ravel() or reshape to the kept-axis dims","Recompute both statistics from the same dataset pass","Verify: assert np.shape(mean) == np.shape(variance)"],"exampleFix":"// before\nlayer = Normalization(axis=-1, mean=mu, variance=var)  # (768,) vs (1,768)\n// after\nimport numpy as np\nlayer = Normalization(axis=-1, mean=np.ravel(mu), variance=np.ravel(var))","handlingStrategy":"validation","validationCode":"import numpy as np\nif np.shape(mean) != np.shape(variance):\n    mean, variance = np.ravel(mean), np.ravel(variance)\nassert np.shape(mean) == np.shape(variance)","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Compute both statistics in the same pass over data","ravel() both arrays defensively"],"tags":["keras","normalization","shape-validation"],"backgroundTag":"array-shape-mismatch","analyzedSha":"7a34a03db60bf60042242d6a556fc3be119046a5","analyzedAt":"2026-08-25T21:25:25.994Z","schemaVersion":2},"datasetVersion":"2026-08-26T02:17:13.382Z"}