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

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

我正在尝试对两个输入 x、y 执行机器学习非线性回归。我正在试穿。问题在于对给定输入的拟合度评估。

我的代码:

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])

当前输出:

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'

您正试图将一个列表乘以一个浮点数,这不是一个有效的运算。错误消息表明您 可以 将序列乘以整数类型但会重复列表,而不是执行逐元素乘法:

>>> 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'

如果要将每个元素乘以浮点数,请使用生成器表达式或将列表转换为 numpy 数组:

>>> [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.])