Python scipy:** 或 pow() 不支持的操作数类型:“list"和“list" [英] Python scipy: unsupported operand type(s) for ** or pow(): 'list' and 'list'

查看:74
本文介绍了Python scipy:** 或 pow() 不支持的操作数类型:“list"和“list"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将函数拟合到数据数组并获得该函数方程的最佳系数.我使用 scipy 库中的 curve_fit 方法.它基于最小二乘法.

I need to fit function to array of data and get optimal coefficients of an equation of this function. I use curve_fit method from scipy library. It is based on least squares method.

import numpy as np 
from scipy.optimize import curve_fit

#This is my function from which i need to get optimal coefficients 'a' and 'b'
def func(x, a, b):  
return a*x**(b*x)

#the arrays of input data                               
x = [1,2,3,4,5]
y =[6,7,8,9,10]

#default (guess) coefficients
p0 = [1, 1] 

popt, pcov = curve_fit(func, x, y, p0)
print popt

它返回以下错误

类型错误:不支持 ** 或 pow() 的操作数类型:'list' 和 'list'

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

但是当我使用另一个更简单的功能而无需电源操作时它可以工作

But when I use the other, more simple function with no power operation it works

def func(x, a, b):  
return a*x + b

它必须尝试将数字组合为整个输入数据数组的幂

It must be trying to bulid number to a power of an entire array of input data

怎么办?请帮助...

推荐答案

看起来你在追求元素级的力量提升?

It looks like you're after element-wise power-raising?

喜欢 a*x[i]**(b*x[i]) 对于每个 i?

Like a*x[i]**(b*x[i]) for each i?

在这种情况下,您必须使用 np.power 函数:

In that case, you have to use the np.power function:

def func(x,a,b):
    return a*np.power(x,b*x)

然后就可以了.

(顺便说一句,将 xy 从列表转换为 numpy 数组可能是值得的:np.array(x)).

(As an aside, it may be worthwhile to convert x and y from lists to numpy arrays: np.array(x)).

这篇关于Python scipy:** 或 pow() 不支持的操作数类型:“list"和“list"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆