Mainland
Mainland

Reputation: 4584

TypeError: can't multiply sequence by non-int of type 'numpy.float64' in Machine learning Non-linear regression

I am trying to perform Machinelearning non-linear regression on two inputs x,y. I am getting the fitting. The problem is with the evalation of the fit for given input.

My code:

x,y = [0,1,2,3,3.8],[0,0,2,6,10]
t1 = x
ym1 = y
# define function for fitting
def EvaluateEqu(t,c0,c1,c2,c3):         # Evaluate c0 + c1*t - c2*e^(-c3*t)
    return c0+c1*t-c2*np.exp(-c3*t)
# find optimal parameters
p01 = [10,1,10,0.01]# initial guesses
c1,cov1 = curve_fit(EvaluateEqu,t1,ym1,p01)  # fit model
# print parameters
print('Optimal parameters')
print(c1) # 
# calculate prediction
yp1 = EvaluateEqu(t1,c1[0],c1[1],c1[2],c1[3])

Present output:

Optimal parameters
[ 9.24814462e+00  2.67773867e+00  1.08963197e+01 -9.15178702e-06]
Traceback (most recent call last):

  File "<ipython-input-15-e40604698a1f>", line 15, in <module>
    yp1 = EvaluateEqu(t1,c1[0],c1[1],c1[2],c1[3])

  File "<ipython-input-15-e40604698a1f>", line 6, in EvaluateEqu
    return c0+c1*t-c2*np.exp(-c3*t)

TypeError: can't multiply sequence by non-int of type 'numpy.float64'

Upvotes: 1

Views: 7220

Answers (1)

bogatron
bogatron

Reputation: 19179

You are trying to multiply a list by a float, which is not a valid operation. The error message indicates that you can multiply the sequence by an integer type but that repeats the list, rather than performing element-wise multiplication:

>>> x = [1, 2, 3]
>>> 2 * x
[1, 2, 3, 1, 2, 3]
>>> 2.0 * x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'

If you want to multiply each element by a float, either use a generator expression or convert the list to a numpy array:

>>> [2.0 * xx for xx in x]
[2.0, 4.0, 6.0]
>>> import numpy as np
>>> 2.0 * np.array(x)
array([2., 4., 6.])

Upvotes: 4

Related Questions