Python實現曲線擬合的最小二乘法

2022-10-04 13:06:15 字數 4095 閱讀 4555

模組匯入

import numpy as np

import gaosi as gs

**"""

本函式通過建立增廣矩陣,並呼叫高斯列主元消去法模組進行求解。

"""import numpy as np

import gaosi as gs

shape = int(input('請輸入擬合函式的次數:'))

x = np.array([0.6,1.3,1.64,1.8,2.1,2.3,2.44])

y = np.array([7.05,12.2,14.4,15.2,17.4,19.6,20.2])

data =

for i in range(shape*2+1):

if i != 0:

data.append(np.sum(x**i))

else:

data.append(len(x))

b =

for i in range(shape+1):

if i != 0:

b.append(np.sum(y*x**i))

else:

b.append(np.sumwww.cppcns.com(y))

b = np.array(b).reshape(shape+1,1)

n = np.zeros([shape+1,shape+1])

for i in range(shape+1):

for j in range(shape+1):

n[i][j] = data[i+j]

result = gs.handle(n,b)

if not result:

print('增廣矩陣求解失敗!')

exit()

fun='f(x) = '

for i in range(len(result)):

if type(result[i]) == type(''):

print('存在自由變數!')

fun = fun + str(result[i])

elif i == 0:

fun = fun + ''.format(result[i])

else:

fun = fun + '+*x^'.format(result[i],i)

print('求得次擬合函式為:'.format(shape))

print(fun)

高斯模組

# 匯入 numpy 模組

import numpy as np

# 行交換

def swap_row(matrix, i, j):

m, n = matrix.shape

if i >= m or j >= m:

print(www.cppcns.com'錯誤! : 行交換超出範圍 ...')

else:

matrix[i],matrix[j] = matrix[j].copy(),matrix[i].copy()

return matrix

# 變成階梯矩陣

def matrix_change(matrix):

m, n = matrix.shape

main_factor =

main_col = main_row = 0

while main_row < m and main_col < n:

# 選擇進行下一次主元查詢的列

main_row = len(main_factor)

# 尋找列中非零的元素

not_zeros = np.where(abs(matrix[main_row:,main_col]) > 0)[0]

# 如果該列向下全部資料為零,則直接跳過列

if len(not_zeros) == 0:

main_col += 1

continue

else:

# 將主元列號儲存在列表中

main_factor.append(main_col)

# 將第乙個非零行交換至最前

if not_zeros[0] != [0]:

matrix = swap_row(matrix,main_row,main_row+not_zeros[0])

# 將該列主元下方所有元素變為零

if main_row < m-1:

for k in range(main_row+1,m):

a = float(matrix[k, main_col] / matrix[main_row, main_col])

matrix[k] = matrix[k] - matrix[main_row] * matrix[k, main_col] / matrix[main_r main_col]

main_col += 1

return matrix,main_factor

# 回代求解

def back_solve(matrix, main_factor):

# 判斷是否有解

if len(main_factor) == 0:

print('主元錯誤,無主元! ...')

return none

m, n = matrix.shape

if main_factor[-1] == n - 1:

print('無解! ...')

return none

# 把所有的主元元素上方的元素變成0

for i in range(len(main_factor) - 1, -1, -1):

factor = matrix[i, main_factor[i]]

matrix[i] = matrix[i] / float(factor)

for j in range(i):

times = matrix[j, main_factor[i]]

matrix[j] = matrix[j] - float(times) * matrix[i]

# 先看看結果對不對

return matrix

# 結果列印

def print_result(matrix, main_factor):

if matrix is none:

print('階梯矩陣為空! ...')

return none

m, n = matrix.shape

result = [''] * (n - 1)

main_factor = list(main_factor)

for i in range(n - 1):

# 如果不是主元列,則為自由變數

if i not in main_factor:

result[i] = '(free var)'

# 否則是主元變數,從對應的行,將主元變數表示成非主元變數的線性組合

else:

# row_of_main表示該主元所在的行

row_of_main = main_factor.index(i)

result[i] = matrix[row_of_main, -1]

return result

# 得到簡化的階梯矩陣和主元列

def handle(matrix_a, matrix_b):

# 拼接成增廣矩陣

matrix_01 = np.hstack([matrwww.cppcns.comix_a, matrix_b])

matrix_01, main_factor = matrix_change(matrix_01)

matrix_01 = back_solve(matrix_01, main_factor)

result = print_result(matrix_01, main_factor)

return result

if __name__ == '__main__':

a = np.array([[2, 1, 1], [3, 1, 2], [1, 2, 2]],dtype=float)

b = np.array([[4],[6],[5]],dtype=float)

a = handle(a, b)

本文標題: python實現曲線擬合的最小二乘法

本文位址:

Python曲線擬合

z1 np.polyfit x,y,5 用3次多項式擬合 p1 np.poly1d z1 print p1 在螢幕上列印擬合多項式 yvals p1 x 也可以使用yvals np.polyval z1,x plot1 plt.plot x,y,k.markersize 16,label origi...

python曲線擬合

python中曲線擬合 乙個是numpy中的polyfit 函式,多項式擬合,給定變數x y 多項式次數,返回值為多項式的一維係數array 另乙個是scipy的 optimize 模組中的 curve fit 函式,可由自己定義擬合函式,更通用 給定變數x y 擬合函式,返回值有兩個,popt是擬...

最小二乘曲線擬合matlab實現

對如下圖所示的加雜訊曲線,如何進行曲線擬合呢?我們可以採用 階多項式去逼近它 係數隨機資料的產生如下 function y truth,y observed unknown model1 x y truth 0.001 x.4 x.3 5 x.2 0.5 x 4階的資料 y observed y t...