34

I'm trying to use SkLearn Bayes classification.

 gnb = GaussianNB()
 gnb.set_params('sigma__0.2')
 gnb.fit(np.transpose([xn, yn]), y)

But I get:

set_params() takes exactly 1 argument (2 given)

now I try to use this code:

gnb = GaussianNB()
arr = np.zeros((len(labs),len(y)))
arr.fill(sigma)
gnb.set_params(sigma_ = arr)

And get:

ValueError: Invalid parameter sigma_ for estimator GaussianNB

Is it wrong parameter name or value?

Leonid
  • 1,127
  • 2
  • 15
  • 29

5 Answers5

67

I just stumbled upon this, so here is a solution for multiple arguments from a dictionary:

from sklearn import svm
params_svm = {"kernel":"rbf", "C":0.1, "gamma":0.1, "class_weight":"auto"}
clf = svm.SVC()
clf.set_params(**params_svm)
Kam Sen
  • 1,098
  • 1
  • 11
  • 14
  • been waiting years to figure this out. See this answer for more details on how this works: https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters – Kermit Oct 23 '20 at 00:25
  • This is what I was searching for – Quinten C May 30 '21 at 12:43
24

set_params() takes only keyword arguments, as can be seen in the documentation. It is declared as set_params(**params).

So, in order to make it work, you need to call it with keyword arguments only: gnb.set_params(some_param = 'sigma__0.2')

Mezgrman
  • 876
  • 6
  • 11
4

It is written in documentation that the syntax is:

set_params(**params)

These two stars mean that you need to give keyword arguments (read about it here). So you need to do it in the form your_param = 'sigma__0.2'

Community
  • 1
  • 1
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • Yes, this is the correct answer. The python error is misleading and should say you should provide kwargs – N4ppeL Jul 26 '23 at 13:14
3

sigma_ is an instance attribute which is computed during training. You probably aren't intended to modify it directly.

from sklearn.naive_bayes import GaussianNB
import numpy as np

X = np.array([[-1,-1],[-2,-1],[-3,-2],[1,1],[2,1],[3,2]])
y = np.array([1,1,1,2,2,2])

gnb = GaussianNB()
print gnb.sigma_

Output:

AttributeError: 'GaussianNB' object has no attribute 'sigma_'

More code:

gnb.fit(X,y) ## training
print gnb.sigma_

Output:

array([[ 0.66666667,  0.22222223],
       [ 0.66666667,  0.22222223]])

After training, it is possible to modify the sigma_ value. This might affect the results of prediction.

gnb.sigma_ = np.array([[1,1],[1,1]])
Brent Bradburn
  • 51,587
  • 17
  • 154
  • 173
2

The problem here is that GaussianNB has only one parameter and that is priors.

From the documentation

 class sklearn.naive_bayes.GaussianNB(priors=None)

The sigma parameter you are looking for is, in fact, an attribute of the class GaussianNB, and cannot be accessed by the methods set_params() and get_params().

You can manipulate sigma and theta attributes, by feeding some Priors to GaussianNB or by fitting it to a specific training set.

Pedro Baracho
  • 357
  • 1
  • 12