使用scipy优化同时优化两个数组

时间:2016-03-17 11:54:58

标签: python arrays numpy optimization

我有一个函数,需要两个m维数组用它们进行一些计算(这里非常简化)并返回一维数组。此外,我有m维测量数据,并希望优化这两个阵列以适应测量。这适用于一个阵列。我只是不能让它与两个数组(或更多)一起工作。它总是抛出:

TypeError: Improper input: N=40 must not exceed M=20

这是我的代码。非常感谢,如果有人可以帮忙的话!

import numpy as np
from scipy import optimize

data=[np.arange(0,20.0,1),np.array([-52.368, 32.221, 40.102, 48.088, 73.106, 50.807, 52.235, 76.933, 65.737, 34.772, 94.376, 123.366, 92.71, 72.25, 165.051, 91.501, 118.92, 100.936, 56.747, 159.034])]

def line(m,b):
   return m*b

guessm = np.ones(20)               #initial guessed values for m
guessb = np.ones(20)               #initial guesses values for b
guess = np.append(guessm,guessb)

errfunc= lambda p,y: (y-line(p[:20],p[20:]))
parameter, sucess = optimize.leastsq(errfunc, guess, args=(data[1]))

print(parameter)
plt.plot(data[0],d[1],'o')
plt.plot(data[0],line(parameter[0],parameter[1]))
plt.show()

1 个答案:

答案 0 :(得分:1)

如果你想拟合一条线,你应该给出斜率和截距 - 两个参数,而不是40个。我怀疑这是你试图做的:

import matplotlib.pyplot as plt
import numpy as np
from scipy import optimize

data=[np.arange(0,20.0,1),np.array([-52.368, 32.221, 40.102, 48.088, 73.106, 50.807, 52.235, 76.933, 65.737, 34.772, 94.376, 123.366, 92.71, 72.25, 165.051, 91.501, 118.92, 100.936, 56.747, 159.034])]

def line(m,b):
   return np.arange(0, 20, 1)*m + b

guess = np.ones(2)

errfunc= lambda p,y: (y-line(p[0],p[1]))
parameter, sucess = optimize.leastsq(errfunc, guess, args=(data[1]))

print(parameter)
plt.plot(data[0],data[1],'o')
plt.plot(data[0],line(parameter[0],parameter[1]))
plt.show()