Created
May 8, 2013 15:53
-
-
Save nicoguaro/5541416 to your computer and use it in GitHub Desktop.
Compute the least square fitting for a function of two variables and also the coefficient of determination (R**2).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from scipy import zeros, dot, linspace, linalg, array, sqrt, loadtxt, meshgrid | |
from scipy import shape, mean | |
from numpy.linalg import norm | |
from scipy.optimize import minimize | |
x = loadtxt('x.txt') | |
t = loadtxt('t.txt') | |
S = loadtxt('Syy.txt') | |
X, T = meshgrid(x,t) | |
def fun(x): | |
S2 = x[0]*sqrt(T/X) + x[1]/sqrt(X) + x[2] | |
return norm(S - S2) | |
def coeff_det(x): | |
Savg = mean(S) | |
S2 = x[0]*sqrt(T/X) + x[1]/sqrt(X) + x[2] | |
Serr = 0.0 | |
Stot = 0.0 | |
for i in range(0,shape(S)[0]): | |
for j in range(0,shape(S)[1]): | |
Serr = Serr + (S[i,j] - S2[i,j])**2 | |
Stot = Stot + (S[i,j] - Savg)**2 | |
return 1 - Serr/Stot | |
x0 = [0.37*sqrt(2.0),0.2214,-0.9608] | |
res = minimize(fun, x0, method='SLSQP') | |
print res.message | |
print "The solution found is: ", res.x | |
print "The relative error is: ", fun(res.x)/norm(S) | |
print "The coefficient of determination is (R**2): ", coeff_det(res.x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment