TypeError: unsupported operand type(s) for ** or pow(): 'module' and 'int'

Hi Team,

In Chapter 4 under End to End SGD topic I got the below error while executing the code. How can I fix this?

def f(t, params):
a,b,c = params
return a*(t**2) + (b*t) + c

def mse(preds, targets): return ((preds-targets)**2).mean()

params = torch.randn(3).requires_grad_()
preds = f(time, params)

TypeError Traceback (most recent call last)
in
----> 1 preds = f(time, params)

in f(t, params)
1 def f(t, params):
2 a,b,c = params
----> 3 return a*(t**2) + (b*t) + c
4
5 def mse(preds, targets): return ((preds-targets)**2).mean()

TypeError: unsupported operand type(s) for ** or pow(): ‘module’ and ‘int’

Hi
On the text above you do not have indentation but that might just be copy and paste.
So it should be
def t(t,params)
a,b,c=params
return a*(t**2)+(b*t)+c

The rather meaningless message means there is a module called “t” and you are trying to raise it to a power. You probably think preds or targets are variables but thinks it is a module. Try using type() on the variables but I think you have a typing error somewhere which has confused Python.

Regards Conwyn

1 Like

Hi Conwyn,
Thanks for the guidance, I explored further using type() function and found that I was inadvertently trying to take square of time module, which is not allowed by python.
In the below function i did (preds-targets)**2 and then used preds as a function of time

def mse(preds, targets): return ((preds-targets)**2).mean()
preds = f(time, params)

I guess I just need to rename time to some other name so that python does not mistake it for the module. Am I thinking in right direction?

I fixed the above error by converting the time module to a tensor as described in the book.

Regards
Anand