TypeError:在机器学习非线性回归中,无法将序列与“numpy.float64”类型的非整数相乘

2024-04-25 18:03:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试对两个输入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'

Tags: returnnpoptimalfitparameterst1printc2
1条回答
网友
1楼 · 发布于 2024-04-25 18:03:32

您试图将列表与浮点相乘,这是无效的操作。错误消息表明您可以将序列乘以整数类型,但会重复列表,而不是执行元素乘法:

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

相关问题 更多 >