Home » Solving “set_params() takes 1 positional argument but 2 were given”

Solving “set_params() takes 1 positional argument but 2 were given”

  • by
  • 2 min read

Brief blog post on a silly Python error. I’m still working on my ML project started hypertuning my sklearn pipeline — manually. To set the parameters of my pipeline in every iteration, I had to use set_params.

My estimator is called model_pipeline and I needed to set the parameters via a dictionary for a particular situation, via the set_params method.

model_pipeline.set_params(params)

I expected it to work. But when I ran that line of code, this is the error that I ran into:

set_params() takes 1 positional argument but 2 were given

It’s a common Python error, not specifically tied to a Pipeline or even scikit-learn, that I’ll spend some time on in this blog post.


If you consult the set_params documentation, you will read the following:

set_params(**kwargs)      Set the parameters of this estimator.

See those two asterisks? You probably have already encountered it in a Python function’s documentation; they’re actually pretty important if you want to use Python efficiently.

  • *args: accepts any number of positional arguments via a tuple
  • **kwargs: accepts any number of keyword arguments via a dictionary

The arguments args and kwargs are variables and will contain, respectively, the tuple or dictionary that you pass it. You can even name them whatever you want — but only if you want to piss off someone from your team. The following code will simply print the dictionary I passed to the badger function.

def badger(**fruit):
    return fruit

badger(**{'apples': 4, 'pears': 3})

And if you want to piss off not only your colleague, but your whole team, try mixing both of them with regular arguments in a random position — really, don’t.

def badger(mice, ants = None, *fruit, eggs = None, **vegetables): 
    return mouse, ant, fruit, egg, plants
  
badger(6, 7, ants = *(8, 9, 10, 11, 12), 13, 14, fruit = **{'broccoli': 15, 'cabbage': 16})

There we go. From a very specific situation to a very general blog post. Hope you learned something.

Say thanks, ask questions or give feedback

Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.

Leave a Reply

Your email address will not be published. Required fields are marked *