Swift
Swift

Reputation: 360

Optimising two arrays simultaneously with scipy optimize

I have a function that takes two m-dimensional arrays does some calculation with them (here it is very simplified) and returns one dimensional array. Also I have m-dimensional measurement data and would like to optimise those two arrays to fit the measurements. This worked fine with one arrays. I can just simply not get it to work with two arrays (or more). it always throws:

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

Here is my Code. Thank you very much if anyone can help!

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

Upvotes: 0

Views: 1153

Answers (1)

sulkeh
sulkeh

Reputation: 947

If you want to fit a line, you should give the slope and intercept - two parameters, not 40. I suspect this is what you try to do:

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

Upvotes: 1

Related Questions