2017-02-06 156 views
0

我想找到some_arg值,將盡量減少功能。蟒蛇scipy蠻力優化

1)出口

from scipy import optimize 
import math as m 

2)計算原始2 * SIN(t)的數據

time_steps = list(range(0,20)) 

def my_sin(time_steps): 
    sin_data = list() 
    for time_step in time_steps: 
     sin_data.append(2*m.sin(time_step)) 
    return sin_data 

my_sin_data = my_sin(time_steps) 

3)設定錯誤我希望儘量減少

def fun_to_brute(z, *params): 
    some_argument = z 
    sum_of_errors = 0 
    for time_step in params[0]: 
     sum_of_errors = sum_of_errors + some_argument*m.sin(time_step) - params[1][time_step] 
    return sum_of_errors 

4)最後開始蠻力

rranges = [slice(-4, 4, 0.25)] 
params = (time_steps, my_sin_data) 
resbrute = optimize.brute(fun_to_brute, rranges, args = params, full_output=True) 

但我得到的結果是錯誤的。我想蠻力使some_arg值2,在這種情況下,sum_of_errors _必須等於零。

但resbrute [0]會返回一些奇怪的值

+0

爲什麼那裏是熊貓嗎?它只是無處不在... – Benjamin

+0

忘記刪除 – Demaunt

+0

嘗試添加'finish = None'到otpimize.brute – Xevaquor

回答

1

如果我讀這個權利,你只是想恢復您在原始數據應用的2的縮放因子。

你可以簡化一些東西。請注意,範圍和參數參數要求元組。還要注意,你正在尋找的東西應該是你正在調用的函數的主要參數。

通常你會通過比較模型之間的差異最小化殘差平方或一些其他錯誤措施的總和,因爲它是使用parameter_of_interest計算,因爲它是在你的實驗數據:

import numpy 
import scipy 
from scipy import optimize 

def f(param_of_interest, *args): 

    sin_data = args[0] 
    time_steps = args[1] 

    model = param_of_interest * numpy.sin(time_steps) 
    ssq_residuals = numpy.sum((model - sin_data) ** 2) 
    return ssq_residuals 

# Your input data 
time_steps = numpy.arange(20) 
factor = 2 
sin_data = factor * numpy.sin(time_steps) 

result= scipy.optimize.brute(f, 
          (slice(-4, 4, 0.25),), 
          args=(sin_data, time_steps), 
          full_output=True) 
print(result) # Gives expected answer of 2.