votes up 1

`weights` input should be one-dimensional.

Package:
scipy
github stars 8546
Exception Class:
ValueError

Raise code

        self.d, self.n = self.dataset.shape

        if weights is not None:
            self._weights = atleast_1d(weights).astype(float)
            self._weights /= sum(self._weights)
            if self.weights.ndim != 1:
                raise ValueError("`weights` input should be one-dimensional.")
            if len(self._weights) != self.n:
                raise ValueError("`weights` input should be of length n")
            self._neff = 1/sum(self._weights**2)

        self.set_bandwidth(bw_method=bw_method)

    def evaluate(self, points):
😲 Agile task management is now easier than calling a taxi. #Tracklify
🙏 Scream for help to Ukraine
Today, 2nd July 2022, Russia continues bombing and firing Ukraine. Don't trust Russia, they are bombing us and brazenly lying in same time they are not doing this 😠, civilians and children are dying too! We are screaming and asking exactly you to help us, we want to survive, our families, children, older ones.
Please spread the information, and ask your governemnt to stop Russia by any means. We promise to work extrahard after survival to make the world safer place for all.

Ways to fix

votes up 2 votes down

This happens if weight is given a 2D array. The valid value is a 1D array with the same length as the dataset array.

How to reproduce the error:

pipenv install scipy numpy

from scipy import stats
import numpy as np
dataset = np.random.randint(1,10,10)
weigts = np.random.rand(10,1) # this one should be 1D, instead it is given 2D array shpaed (10,1)

kernel = stats.gaussian_kde(dataset,weights=weigts)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-18-60df39608b5e> in <module>()
      3 dataset = np.random.randint(1,10,10)
      4 weigts = np.random.rand(10,1)
----> 5 kernel = stats.gaussian_kde(dataset,weights=weigts)

/usr/local/lib/python3.7/dist-packages/scipy/stats/kde.py in __init__(self, dataset, bw_method, weights)
    199             self._weights /= sum(self._weights)
    200             if self.weights.ndim != 1:
--> 201                 raise ValueError("`weights` input should be one-dimensional.")
    202             if len(self._weights) != self.n:
    203                 raise ValueError("`weights` input should be of length n")

ValueError: `weights` input should be one-dimensional.

Fixed:

from scipy import stats
import numpy as np
dataset = np.random.randint(1,10,10)
weigts = np.random.rand(10)
kernel = stats.gaussian_kde(dataset,weights=weigts)
Sep 05, 2021 kellemnegasi answer
kellemnegasi 30.0k

Add a possible fix

Please authorize to post fix