決策樹

決策樹

原理

決策樹是屬於機器學習監督學習分類算法中比較簡單的一種,決策樹是一個預測模型;他代表的是對象屬性與對象值之間的一種映射關係。樹中每個節點表示某個對象,而每個分叉路徑則代表的某個可能的屬性值,而每個葉結點則對應從根節點到該葉節點所經歷的路徑所表示的對象的值。
優點:1、很容易將模型進行可視化;2、不需要對數據進行轉換
缺點:1、容易出現過擬合現象

具體用法
import numpy as np
import matplotlib.pyplot as plt
from sklearn import tree, datasets
from sklearn.model_selection import train_test_split


def decision_tree1():
    wine = datasets.load_wine()
    X = wine.data[:, :2]
    y = wine.target
    X_train, X_test, y_train, y_test = train_test_split(X, y)
    clf = tree.DecisionTreeClassifier(max_depth=3)
    clf.fit(X_train, y_train)
    print(clf)

    # 分別用樣本的兩個特徵值創建圖像的橫軸和縱軸
    x_min, x_max = X_train[:, 0].min() - 1, X_train[:, 0].max() + 1
    y_min, y_max = X_train[:, 1].min() - 1, X_train[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, .02),
                         np.arange(y_min, y_max, .02))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    # 給每個分類中的樣本分配不同的顏色
    Z = Z.reshape(xx.shape)
    plt.figure()
    plt.pcolormesh(xx, yy, Z)

    plt.scatter(X[:, 0], X[:, 1], c=y, edgecolors='k', s=20)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.title('decision_tree')
    plt.show()

運行結果

DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=3,
            max_features=None, max_leaf_nodes=None,
            min_impurity_decrease=0.0, min_impurity_split=None,
            min_samples_leaf=1, min_samples_split=2,
            min_weight_fraction_leaf=0.0, presort=False, random_state=None,
            splitter='best')

隨機森林

原理

隨機森林就是用隨機的方式建立一個森林,在森林裏有很多決策樹組成,並且每一棵決策樹之間是沒有關聯的。當有一個新樣本的時候,我們讓森林的每一棵決策樹分別進行判斷,看看這個樣本屬於哪一類,然後用投票的方式,哪一類被選擇的多,作爲最終的分類結果。在迴歸問題中,隨機森林輸出所有決策樹輸出的平均值。
優點:1、不需要對數據進行轉換;2、能彌補決策樹容易出現過擬合的不足;3、支持並行處理

具體用法
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split


def random_forest1():
    wine = datasets.load_wine()
    X = wine.data[:, :2]
    y = wine.target
    # 將數據集拆分爲訓練集和測試集
    X_train, X_test, y_train, y_test = train_test_split(X, y)
    # 設定樹的個數 n_estimators; n_jobs=-1 自動使用CPU的全部內核,並行處理
    forest = RandomForestClassifier(n_estimators=6, random_state=3, n_jobs=-1)
    forest.fit(X_train, y_train)
    print(forest)

    # 分別用樣本的兩個特徵值創建圖像的橫軸和縱軸
    x_min, x_max = X_train[:, 0].min() - 1, X_train[:, 0].max() + 1
    y_min, y_max = X_train[:, 1].min() - 1, X_train[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, .02),
                         np.arange(y_min, y_max, .02))
    Z = forest.predict(np.c_[xx.ravel(), yy.ravel()])
    # 給每個分類中的樣本分配不同的顏色
    Z = Z.reshape(xx.shape)
    plt.figure()
    plt.pcolormesh(xx, yy, Z)

    plt.scatter(X[:, 0], X[:, 1], c=y, edgecolors='k', s=20)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.title('random_forest')
    plt.show()

運行結果

RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
            max_depth=None, max_features='auto', max_leaf_nodes=None,
            min_impurity_decrease=0.0, min_impurity_split=None,
            min_samples_leaf=1, min_samples_split=2,
            min_weight_fraction_leaf=0.0, n_estimators=6, n_jobs=-1,
            oob_score=False, random_state=3, verbose=0, warm_start=False)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章