votes up 1

Invalid number of features (%d).

Package:
Exception Class:
ValueError

Raise code

    def _validate_params(n_features, input_type):
        # strangely, np.int16 instances are not instances of Integral,
        # while np.int64 instances are...
        if not isinstance(n_features, numbers.Integral):
            raise TypeError("n_features must be integral, got %r (%s)."
                            % (n_features, type(n_features)))
        elif n_features < 1 or n_features >= np.iinfo(np.int32).max + 1:
            raise ValueError("Invalid number of features (%d)." % n_features)

        if input_type not in ("dict", "pair", "string"):
            raise ValueError("input_type must be 'dict', 'pair' or 'string',"
                             " got %r." % input_type)

    def fit(self, X=None, y=None):
        """No-op. """
😲 Agile task management is now easier than calling a taxi. #Tracklify
🙏 Scream for help to Ukraine
Today, 25th May 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 3 votes down

The value of the n_features parameter should be between 1 and np.iinfo(np.int32).max + 1

This means the maximum value is 2147483648 and the minimum value is 1

Code to reproduce this exception:

from sklearn.feature_extraction import FeatureHasher
h = FeatureHasher(n_features=0)
D = [{'dog': 1, 'cat':2, 'elephant':4},{'dog': 2, 'run': 5}]
f = h.transform(D)
f.toarray()

Error output:

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-19-982ee2b8f99e> in <module>()  1 from sklearn.feature_extraction import FeatureHasher ----> 2 h = FeatureHasher(n_features=0)  3 D = [{'dog': 1, 'cat':2, 'elephant':4},{'dog': 2, 'run': 5}]  4 f = h.transform(D)  5 f.toarray() 
/usr/local/lib/python3.7/dist-packages/sklearn/feature_extraction/_hash.py in _validate_params(n_features, input_type)  118 )  119 elif n_features < 1 or n_features >= np.iinfo(np.int32).max + 1: --> 120 raise ValueError("Invalid number of features (%d)." % n_features)  121   122 if input_type not in ("dict", "pair", "string"): 
ValueError: Invalid number of features (0).

Fixed version of the code:

from sklearn.feature_extraction import FeatureHasher
h = FeatureHasher(n_features=7)
D = [{'dog': 1, 'cat':2, 'elephant':4},{'dog': 2, 'run': 5}]
f = h.transform(D)
f.toarray()

output:

array([[ 0., 0., 2., 0., 0., -1., -4.], [ 0., 0., 0., 0., 0., -7., 0.]])

May 05, 2022 kellemnegasi answer
kellemnegasi 29.0k

Add a possible fix

Please authorize to post fix