简体   繁体   中英

Optimizing Parameter by Minimizing Chi-Square Error?

I need to create a function that optimizes a parameter, beta, by minimizing the chi-square error.

My equation would be error = vg(r) + (beta/3)*H/(1+z) r delta(r)

I have data for vg(r), delta(r), and r itself. H and z are known parameters, and I can guess for beta, but I don't know exactly how to implement this in python.

I'm new to python, and could use some help

I've tried using the scipy.optimize.minimize function, but can't seem to get it to work.

import numpy as np
from scipy import optimize as opt
import math

#parameters
z = 1.05352
bias = 1.85
h = 0.676
Om = 0.31
Ol = 1.-Om
pi = math.pi
H = 1.1


#beta = 0.47663662075855323
# ^this is a guess, I need this parameter optimized

def veldif(vr, delta):
    model = -beta/3*H/(1+z)**delta
    d = np.power((vr-model),2)
    quotient = np.divide(d ,model)
    chisquare = np.sum(quotient)
    return chisquare

result = opt.minimize(veldif,beta)

Expected results: an optimized beta value (scalar)

actual results: error (seems to be an error with passing values through the "veldif" function, as well as the syntax of the "veldif" function.

It is not very clear what are your r, vg(r), delta(r) and how are you accessing them. However, your snippet is missing the initial guess for beta , which is supposed to be the variable of your objective function veldif and not vr (if you are searching for the optimal beta). As for vg(r) and delta(r) ; you can define these two as functions that take r as input and return the associated value. This can done as follows:

import numpy as np
from scipy.optimize import minimize


# examples for delta(r) and vg(r)
delta = lambda r:  3*r
vg    = lambda r:  2*r

def veldif(beta, r, H, z):
    model      = (-beta / 3) * (H / (1+z)**delta(r))
    chisquare  = np.sum((vg(r) - model)**2 / model)
    return chisquare

# parameters
z      = 1.05352
H      = 1.1
r      = 1
args   = (r, H, z)
beta0  = 0.2

# minimization
result = minimize(veldif,
                  x0   = beta0, 
                  args = args)
print(result)

For more on how to use scipy.optimize.minimize please refer to the docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM