{"record":{"id":"62dc66b3af759376","repo":"jax-ml/jax","slug":"weights-input-should-be-of-length-n","errorCode":null,"errorMessage":"`weights` input should be of length n","messagePattern":"`weights` input should be of length n","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"jax/_src/scipy/stats/kde.py","lineNumber":71,"sourceCode":"\n  def __init__(self, dataset, bw_method: BwMethod = None, weights=None):\n    check_arraylike(\"gaussian_kde\", dataset)\n    dataset = jnp.atleast_2d(dataset)\n    if dtypes.issubdtype(lax.dtype(dataset), np.complexfloating):\n      raise NotImplementedError(\"gaussian_kde does not support complex data\")\n    if not dataset.size > 1:\n      raise ValueError(\"`dataset` input should have multiple elements.\")\n\n    d, n = dataset.shape\n    if weights is not None:\n      check_arraylike(\"gaussian_kde\", weights)\n      dataset, weights = promote_dtypes_inexact(dataset, weights)\n      weights = jnp.atleast_1d(weights)\n      weights /= jnp.sum(weights)\n      if weights.ndim != 1:\n        raise ValueError(\"`weights` input should be one-dimensional.\")\n      if len(weights) != n:\n        raise ValueError(\"`weights` input should be of length n\")\n    else:\n      dataset, = promote_dtypes_inexact(dataset)\n      weights = jnp.full(n, 1.0 / n, dtype=dataset.dtype)\n\n    self._setattr(\"dataset\", dataset)\n    self._setattr(\"weights\", weights)\n    neff = self._setattr(\"neff\", 1 / jnp.sum(weights**2))\n\n    bw_method = \"scott\" if bw_method is None else bw_method\n    if bw_method == \"scott\":\n      factor = jnp.power(neff, -1. / (d + 4))\n    elif bw_method == \"silverman\":\n      factor = jnp.power(neff * (d + 2) / 4.0, -1. / (d + 4))\n    elif jnp.isscalar(bw_method) and not isinstance(bw_method, str):\n      factor = cast(Array, bw_method)\n    elif callable(bw_method):\n      factor = bw_method(self)\n    else:","sourceCodeStart":53,"sourceCodeEnd":89,"githubUrl":"https://github.com/jax-ml/jax/blob/1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb/jax/_src/scipy/stats/kde.py#L53-L89","documentation":"gaussian_kde weights must have exactly n entries, where n is dataset.shape[1] (the number of samples) after the dataset is made 2-D. Note the length check happens after in-place normalization weights /= jnp.sum(weights), so mismatched weights are rejected here rather than earlier.","triggerScenarios":"Passing weights of length m != dataset.shape[1]; passing a scalar weight; passing weights aligned with a transposed dataset layout.","commonSituations":"Subsampling the dataset but reusing old weights; weights computed against a different split of the data; dataset auto-transposed by atleast_2d so n differs from what the user assumed.","solutions":["Make len(weights) == dataset.shape[1]; check dataset = jnp.atleast_2d(dataset).shape first","If dataset is (n, d) user-side, transpose it or slice weights to match the sample axis","Recompute weights after any filtering/subsampling of the data"],"exampleFix":"// before\nkde = gaussian_kde(X.T, weights=w)  # w computed for X rows, wrong n\n// after\nkde = gaussian_kde(X.T, weights=w[:X.shape[0]])  # or recompute w for kept rows","handlingStrategy":"validation","validationCode":"n = jnp.atleast_2d(jnp.asarray(dataset)).shape[1]\nassert len(weights) == n, f'weights must have length {n}'","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Derive n from atleast_2d(dataset).shape[1] to mirror the library","Recompute weights whenever the dataset is filtered","Add a shape-consistency unit test"],"tags":["jax","scipy","kde","weights","length-mismatch"],"backgroundTag":"length-mismatch","analyzedSha":"1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb","analyzedAt":"2026-08-27T09:53:25.647Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}