user955632
user955632

Reputation: 153

scipy curve fit on a matrix

I need to do a simple curve fitting using scipy's curve_fit function. However, my data is in the form of a matrix. I can easily do this in numpy but I wanted to see the goodness of fit for scipy.

Problem:

AX = B --> given A, find X for least square error.

from scipy.optimize import curve_fit
def getXval():
    a = 4; b = 3, c = 1;
    f0 = a*pow(b, 2)*c
    f1 = a*b/c
    return [f0, f1]

def fit(x, a0, a1):
    res = a0*x[0] + a1*x[1]
    return [res]

x = getXval()
y = [0.15]
popt, pcov = curve_fit(fit, x, y) 

This is, however, not working. Can someone point what is going on here?

Upvotes: 4

Views: 2771

Answers (1)

Javier
Javier

Reputation: 2838

Your code has a few problems.
1) Use numpy arrays instead of Python lists
2) your are missing values for y.

This works for me:

from scipy.optimize import curve_fit
import numpy as np
def getXval():
    a = 4; b = 3; c = 1;
    f0 = a*pow(b, 2)*c
    f1 = a*b/c
    return np.array([f0, f1])

def fit(x, a0, a1):
    res = a0*x[0] + a1*x[1]
    return np.array([res])

x = getXval()
y = np.array([0.15, 0.34])
popt, pcov = curve_fit(fit, x, y)
print popt, pcov

Upvotes: 2

Related Questions