使用matplotlib畫擬合曲線的基本方法

2022-06-24 06:15:09 字數 1907 閱讀 2872

import

matplotlib.pyplot as plt

fig =plt.figure()

ax = fig.add_subplot(111)

ax.scatter(xsortrawarr, ysortrawarr)

ax.plot(xsortrawarr, ysorthatarr)

plt.show()

scatter:畫原始點

plot:畫擬合曲線

這樣就實現了回歸圖的擬合效果圖。

當然由於有很多擬合情況,具體效果還是需要調參,然後看效果,以及十折交叉驗證,選擇乙個泛化最好的演算法

pyplot.plot()

在使用嶺回歸時,發現使用二維陣列作為引數,也可以畫出曲線,例如:yarr = array([[1,2,3,4], [5,6,7,8], [9,10,11,12], [15,16,17,18]])

直接使用yarr的話,將以列資料作為y軸的資料,而x軸,則按照常樣本的個數,進行自然數增長。**為:

import

matplotlib.pyplot as plt

fig =plt.figure()

ax = fig.add_subplot(111)

yarr = array([[1,2,3,4], [5,6,7,8], [9, 10, 11, 12], [15, 16, 17, 18]])

ax.plot(yarr)

plt.show()

結果:

當然,可以使用自定義的x軸資料,如:xarr = arange(10,14,1),這樣的話,就是自定義x軸了。**如下:

import

matplotlib.pyplot as plt

fig =plt.figure()

ax = fig.add_subplot(111)

yarr = array([[1,2,3,4], [5,6,7,8], [9, 10, 11, 12], [15, 16, 17, 18]])

x = arange(10, 14, 1)

ax.plot(x, yarr)

#此時,x軸為4個資料,因為有4個樣本;yarr有4個樣本,4個特徵,特徵值為y軸值

plt.show()

結果如下:

利用plot畫二維資料,有很大的優點:

1.可以比較不同特徵值的變化過程;從這裡可以引申出在不同迭代下權重引數的變化過程。比如在嶺回歸:

cm_regression =cmregression()

abx, aby = cm_regression.loaddataset2('

abalone.txt')

ridgeweights =cm_regression.ridgetest(abx, aby)

xarr = arange(-10, 20, 1)

import

matplotlib.pyplot as plt

fig =plt.figure()

ax = fig.add_subplot(111)

ax.plot(xarr, ridgeweights)

#此時,x軸為xarr有30個資料;ridgeweights 最為y軸值

plt.xlabel('log(lambda)')

plt.show()

執行結果:

matplotlib畫X軸時間的顯示問題

畫時間曲線的函式 defplot curve1 data,title plt.figure figsize 15,5 plt.title title plt.plot data,o plt.show data1,data2 read data 讀取資料 print data1.head 10 列印前...

matplotlib 基本使用

1,plot import matplotlib.pyplot as plt import numpy as np numpy庫,製作資料 x np.linspace 1,1,50 y 2 x 1 plt.plot x,y plot.show linspace x,y,n 範圍 x,y n個點 2,...

matplotlib的基本使用

容器層 1 canvas 畫布,位於最底層,使用者一般接觸不到 2 figure 圖,建立在canvas之上 3 axes 座標系 繪圖區,建立在figure之上,圖形繪製在這個範圍 輔助顯示層 最好放在影象層之後編寫 1 起到輔助作用,提高圖的可讀性 2 網格線,圖例,x y軸的標籤,圖的標籤,刻...