使用遺傳演算法進行曲線擬合

2021-10-23 02:18:23 字數 1394 閱讀 6512

遺傳演算法可以做最優化,這是因為回歸模型的演算法關鍵是最優化,而遺傳演算法可以做最優化。

例如,把殘差當成目標函式,形如 :

min ⁡g

(a,b

)=∑i

=0n(

f(xi

;a,b

)−yi

)2

\min g(a,b)=\sum\limits_^n (f(x_i;a,b)-y_i)^2

ming(a

,b)=

i=0∑

n​(f

(xi​

;a,b

)−yi

​)2然後針對a,b 做優化

我們使用 scikit-opt來程式設計實現,需要安裝 scikit-opt

import numpy as np

import matplotlib.pyplot as plt

from sko.ga import ga

x_true = np.linspace(

-1.2

,1.2,30

)y_true = x_true **

3- x_true +

0.4* np.random.rand(30)

plt.plot(x_true, y_true,

'o')

def

f_fun

(x, a, b, c, d)

:return a * x **

3+ b * x **

2+ c * x + d

defobj_fun

(p):

a, b, c, d = p

residuals = np.square(f_fun(x_true, a, b, c, d)

- y_true)

.sum()

return residuals

ga = ga(func=obj_fun, n_dim=4, size_pop=100, max_iter=500,

lb=[-2] * 4, ub=[2] * 4)

best_params, residuals = ga.run()

print('best_x:', best_params, '\n', 'best_y:', residuals)

y_predict = f_fun(x_true, *best_params)

fig, ax = plt.subplots()

ax.plot(x_true, y_true, 'o')

ax.plot(x_true, y_predict, '-')

plt.show()

參考:

使用遺傳演算法進行曲線擬合

matlab進行曲線擬合

在matlab 中多項式可以通過向量表示 eg f x 4x 3 2x 2 8x 3求解 roots 4,2,8,3 曲線擬合,對離散資料的處理對2點到6點的溫度資料進行分析 分別作出在1,2,3此多項式下的擬合結果分析 x 2 6 y 65 67 72 71 63 morex linspace m...

曲線擬合 使用 ggplot2 進行曲線擬合

有讀者詢問如何對散點圖擬合非線性的曲線。實際上我們通常看到的無論是直線擬合還是各種曲線擬合都屬於廣義線性模型。這裡我們構造一組資料來看看如何使用 ggplot2 來擬合資料。構造的資料因變數大致是自變數 3 次方 set.seed 1234l x y df x x,y y 使用 ggplot2 繪製...

MATLAB 使用 Matlab 進行曲線擬合

在matlab中,用polyfit函式來求得最小二乘擬合多項式的係數,再用polyval函式按所得的多項式計算所給點上的函式近似值。x linspace 0,2 pi,20 y sin x p polyfit x,y,3 y1 polyval p,x plot x,y,o x,y1,legend r...