1. 簡單線性回歸
使用回歸分析繪制擬合曲線是一種常見的方法,簡單線性回歸就是其中的一種。簡單線性回歸可以通過最小二乘法來計(jì)算回歸系數(shù)。以下是一個使用簡單線性回歸來擬合數(shù)據(jù)的代碼示例:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = np.array([2.5, 4.5, 4.8, 5.5, 6.0, 7.0, 7.8, 8.0, 9.0, 9.5])
# 計(jì)算回歸系數(shù)
slope, intercept = np.polyfit(x, y, 1)
# 繪制擬合曲線
plt.scatter(x, y)
plt.plot(x, slope * x + intercept, color='red')
plt.show()
在該代碼中,np.polyfit函數(shù)可以用來計(jì)算簡單線性回歸的回歸系數(shù)。plot函數(shù)用來繪制擬合曲線,scatter函數(shù)繪制原始數(shù)據(jù)點(diǎn)。
2. 多項(xiàng)式回歸
使用多項(xiàng)式回歸是一種常用方法,它可以用來擬合更加復(fù)雜的數(shù)據(jù)集。以下是一個使用多項(xiàng)式回歸來擬合數(shù)據(jù)的代碼示例:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = np.array([2.5, 4.5, 4.8, 5.5, 6.0, 7.0, 7.8, 8.0, 9.0, 9.5])
# 計(jì)算多項(xiàng)式回歸系數(shù)
coefs = np.polyfit(x, y, 3)
# 使用np.poly1d函數(shù)來生成一個多項(xiàng)式擬合對象
poly = np.poly1d(coefs)
# 生成新的橫坐標(biāo),使得擬合曲線更加平滑
new_x = np.linspace(min(x), max(x), 1000)
# 繪制擬合曲線
plt.scatter(x, y)
plt.plot(new_x, poly(new_x), color='red')
plt.show()
與簡單線性回歸不同,多項(xiàng)式回歸可以擬合更加復(fù)雜的數(shù)據(jù)集。在該代碼中,np.polyfit函數(shù)計(jì)算多項(xiàng)式回歸系數(shù),np.poly1d函數(shù)生成一個多項(xiàng)式擬合對象。plot函數(shù)用來繪制擬合曲線,scatter函數(shù)繪制原始數(shù)據(jù)點(diǎn)。
3. 非線性回歸
使用非線性回歸是一種更加復(fù)雜的擬合方法,在實(shí)際應(yīng)用中可以用來擬合更加復(fù)雜的非線性數(shù)據(jù)。以下是一個使用非線性回歸來擬合數(shù)據(jù)的代碼示例:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b, c):
return a * np.exp(-b * x) + c
# 生成模擬數(shù)據(jù)
x_data = np.linspace(0, 4, 50)
y_data = func(x_data, 2.5, 1.3, 0.5) + 0.2 * np.random.normal(size=len(x_data))
# 使用curve_fit函數(shù)來擬合非線性數(shù)據(jù)
popt, pcov = curve_fit(func, x_data, y_data)
# 畫出原始數(shù)據(jù)和擬合曲線
plt.scatter(x_data, y_data, label="Data")
plt.plot(x_data, func(x_data, *popt), color='red', label="Fitted curve")
plt.legend()
plt.show()
在該代碼中,使用了Scipy庫中的curve_fit函數(shù)來擬合非線性數(shù)據(jù)。curve_fit函數(shù)中第一個參數(shù)是非線性函數(shù),第二個參數(shù)是擬合數(shù)據(jù)的橫坐標(biāo),第三個參數(shù)是擬合數(shù)據(jù)的縱坐標(biāo)。
文章來源:http://www.zghlxwxcb.cn/news/detail-504768.html
總結(jié)
以上是Python中的三種常用擬合曲線方法。簡單線性回歸可以擬合線性關(guān)系的數(shù)據(jù),多項(xiàng)式回歸可以擬合更加復(fù)雜的數(shù)據(jù),而非線性回歸則可以用來擬合非線性數(shù)據(jù)。我們可以根據(jù)實(shí)際需要選擇不同的方法來擬合數(shù)據(jù)。文章來源地址http://www.zghlxwxcb.cn/news/detail-504768.html
到了這里,關(guān)于三種用python進(jìn)行線性/非線性擬合的方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!