【问题标题】:TypeError: can't multiply sequence by non-int of type 'numpy.float64' in Machine learning Non-linear regressionTypeError:不能在机器学习非线性回归中将序列乘以“numpy.float64”类型的非整数
【发布时间】:2020-08-02 19:42:00
【问题描述】:

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

【问题讨论】:

    标签: python machine-learning statistics non-linear-regression


    【解决方案1】:

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

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

    【讨论】:

    • 在其他情况下,我一直在使用相同的代码,x、y 尺寸更大,它们都是浮点数。对于这个小的 x,y 列表,我现在很惊讶地收到此错误。
    • 问题不在于序列的大小(即元素的数量)。这个问题是一个列表与 numpy 数组的序列。也许以前的输入是 numpy 数组,而您现在以某种方式获取列表作为输入。
    • 是的!现在我明白了这个问题。你答对了。将列表转换为数组实际上已经解决了这个问题。 np.array(x) 非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 2010-12-30
    • 2012-10-09
    • 1970-01-01
    相关资源
    最近更新 更多