python 分類問題決策邊界視覺化

2021-10-02 18:06:01 字數 1604 閱讀 3037

以二維平面上的分類問題為例:

真實的決策邊界為背景顏色,圓點的顏色表示了乙個隨機模型賦予的標籤。

下面展示如何繪製上圖:

首先需要兩個函式給樣本打標籤:

def

f_true

(x):

return

(np.

sum(x*x,axis=1)

<

0.25

).astype(np.

int)

deff_random

(x):

return np.random.randint(0,

2,[len

(x),1]

)

import matplotlib as mpl

cm_light = mpl.colors.listedcolormap(

['y'

,'r'])

x = np.random.uniform(-1

,1,[

100,2]

)# 在樣本的上下界基礎上擴張一點點

defregion

(a, b)

:return

1.05

*a-0.05

*b,1.05

*b-0.05

*ax1_min, x1_max = region(x[:,

0].min()

, x[:,

0].max()

)# x1的範圍

x2_min, x2_max = region(x[:,

1].min()

, x[:,

1].max()

)# x2的範圍

# 在限定的範圍內 colormesh 方法繪製背景顏色

n=500

m=500

t1 = np.linspace(x1_min, x1_max,n)

t2 = np.linspace(x2_min, x2_max,m)

x1, x2 = np.meshgrid(t1, t2)

x_show = np.stack(

(x1.flat, x2.flat)

, axis=

1)

y_hat = f_true(x_show)

# **

y_hat = y_hat.reshape(x1.shape)

# 使之與輸入的形狀相同

plt.figure(facecolor=

'w')

plt.pcolormesh(x1, x2, y_hat, cmap=cm_light)

# **值的顯示

# scatter 繪製樣本

y = f_random(x)

y = np.squeeze(y)

plt.scatter(x[:,

0], x[:,

1], s=

30, c=y, edgecolors=

'k', cmap=cm_light)

邏輯回歸分類器的決策邊界視覺化

最近在覆盤機器學習的內容,課程中最基礎的例子是利用sklearn中的logisticregression 來進行將資料進行分類訓練,並畫出決策邊界,這是課程中的效果圖,下面來說一下我的程式 首先載入資料,練習中給的資料及有三列,x1,x2,y,x1和x2 是特徵屬性,y作為分類的結果,值有兩種 0和...

Python 分類演算法(決策樹,隨機森林)

資訊熵的計算 條件熵的計算 決策樹分類器 criterion 預設是 gini 係數,也可以選擇資訊增益的熵 entropy max depth 樹的深度大小 random state 隨機數種子 method decision path 返回決策樹的路徑 在機器學習中 隨機森林 是乙個包含多個決策...

用決策樹 CART 解決iris分類問題

首先先看iris資料集 sepal.length 花萼長度 sepal.width 花萼寬度 petal.length 花瓣長度 petal.width 花瓣寬度 通過上述4中屬性可以 花卉屬於setosa,versicolour,virginica 三個種類中的哪一類 決策樹 by cart 決策...