machine-learning
  • 機器學習:使用Python
    • 簡介Scikit-learn 機器學習
  • 分類法 Classification
    • Ex 1: Recognizing hand-written digits
    • EX 2: Normal and Shrinkage Linear Discriminant Analysis for classification
    • EX 3: Plot classification probability
    • EX 4: Classifier Comparison
    • EX 5: Linear and Quadratic Discriminant Analysis with confidence ellipsoid
  • 特徵選擇 Feature Selection
    • Ex 1: Pipeline Anova SVM
    • Ex 2: Recursive Feature Elimination
    • Ex 3: Recursive Feature Elimination with Cross-Validation
    • Ex 4: Feature Selection using SelectFromModel
    • Ex 5: Test with permutations the significance of a classification score
    • Ex 6: Univariate Feature Selection
    • Ex 7: Comparison of F-test and mutual information
  • 互分解 Cross Decomposition
  • 通用範例 General Examples
    • Ex 1: Plotting Cross-Validated Predictions
    • Ex 2: Concatenating multiple feature extraction methods
    • Ex 3: Isotonic Regression
    • Ex 4: Imputing missing values before building an estimator
    • Ex 5: ROC Curve with Visualization API
    • Ex 7: Face completion with a multi-output estimators
  • 群聚法 Clustering
    • EX 1: Feature_agglomeration.md
    • EX 2: Mean-shift 群聚法.md
    • EX 6: 以群聚法切割錢幣影像.md
    • EX 10:_K-means群聚法
    • EX 12: Spectral clustering for image segmentation
    • Plot Hierarchical Clustering Dendrogram
  • 支持向量機
    • EX 1:Non_linear_SVM.md
    • [EX 4: SVM_with _custom _kernel.md](SVM/EX4_SVM_with _custom _kernel.md)
  • 機器學習資料集 Datasets
    • Ex 1: The digits 手寫數字辨識
    • Ex 2: Plot randomly generated classification dataset 分類數據集
    • Ex 3: The iris 鳶尾花資料集
    • Ex 4: Plot randomly generated multilabel dataset 多標籤數據集
  • 應用範例 Application
    • 用特徵臉及SVM進行人臉辨識實例
    • 維基百科主要的特徵向量
    • 波士頓房地產雲端評估(一)
    • 波士頓房地產雲端評估(二)
  • 類神經網路 Neural_Networks
    • Ex 1: Visualization of MLP weights on MNIST
    • Ex 2: Restricted Boltzmann Machine features for digit classification
    • Ex 3: Compare Stochastic learning strategies for MLPClassifier
    • Ex 4: Varying regularization in Multi-layer Perceptron
  • 決策樹 Decision_trees
    • Ex 1: Decision Tree Regression
    • Ex 2: Multi-output Decision Tree Regression
    • Ex 3: Plot the decision surface of a decision tree on the iris dataset
    • Ex 4: Understanding the decision tree structure
  • 機器學習:使用 NVIDIA JetsonTX2
    • 從零開始
    • 讓 TX2 動起來
    • 安裝OpenCV
    • 安裝TensorFlow
  • 廣義線性模型 Generalized Linear Models
    • Ex 3: SGD: Maximum margin separating hyperplane
  • 模型選擇 Model Selection
    • Ex 3: Plotting Validation Curves
    • Ex 4: Underfitting vs. Overfitting
  • 半監督式分類法 Semi-Supervised Classification
    • Ex 3: Label Propagation digits: Demonstrating performance
    • Ex 4: Label Propagation digits active learning
    • Decision boundary of label propagation versus SVM on the Iris dataset
  • Ensemble_methods
    • IsolationForest example
  • Miscellaneous_examples
    • Multilabel classification
  • Nearest_Neighbors
    • Nearest Neighbors Classification
Powered by GitBook
On this page
  • 範例目的
  • (一)引入函式庫及建立隨機數據資料
  • 引入函式資料庫
  • 特徵資料
  • 目標資料
  • (二)建立Decision Tree迴歸模型
  • 建立模型
  • 模型訓練
  • 預測結果
  • (三) 繪出預測結果與實際目標圖
  • (四)完整程式碼
  1. 決策樹 Decision_trees

Ex 2: Multi-output Decision Tree Regression

PreviousEx 1: Decision Tree RegressionNextEx 3: Plot the decision surface of a decision tree on the iris dataset

Last updated 6 years ago

範例目的

此範例用決策樹說明多輸出迴歸的例子,利用帶有雜訊的特徵及目標值模擬出近似圓的局部線性迴歸。 若決策樹深度越深(可由max_depth參數控制),則決策規則越複雜,模型也會越接近數據,但若數據中含有雜訊,太深的樹就有可能產生過擬合的情形。 此範例模擬了不同深度的樹,當用帶有雜點的數據可能造成的情況。

(一)引入函式庫及建立隨機數據資料

引入函式資料庫

  • matplotlib.pyplot:用來繪製影像。

  • sklearn.tree import DecisionTreeRegressor:利用決策樹方式建立預測模型。

特徵資料

  • np.random():隨機產生介於0~1之間的亂數

  • RandomState.rand(d0,d1,..,dn):給定隨機亂數的矩陣形狀

  • np.sort將資料依大小排序。

目標資料

  • np.sin(X):以X做為徑度,計算出相對的sine值。

  • ravel():輸出連續的一維矩陣。

  • y[::5, :] += (0.5 - rng.rand(20, 2)):為目標資料加入雜訊點。

import numpy as np
from sklearn.tree import DecisionTreeRegressor
import matplotlib.pyplot as plt

rng = np.random.RandomState(1)
X = np.sort(200 * rng.rand(100, 1) - 100, axis=0) #在-100~100之間隨機建立100個點

y = np.array([np.pi * np.sin(X).ravel(), np.pi * np.cos(X).ravel()]).T #每個X產生兩個輸出分別為sine及cosine值,並存於y中
y[::5, :] += (0.5 - rng.rand(20, 2)) #每5筆資料加入一個雜訊

(二)建立Decision Tree迴歸模型

建立模型

  • DecisionTreeRegressor(max_depth = 最大深度):DecisionTreeRegressor建立決策樹回歸模型。max_depth決定樹的深度,若為None則所有節點被展開。此範例會呈現不同max_depth對預測結果的影響。

模型訓練

  • fit(特徵資料, 目標資料):利用特徵資料及目標資料對迴歸模型進行訓練。

預測結果

  • np.arrange(起始點, 結束點, 間隔):np.arange(-100.0, 100.0, 0.01)在-100~100之間每0.01取一格,建立預測輸入點矩陣。

  • np.newaxis:增加矩陣維度。

  • predict(輸入矩陣):對訓練完畢的模型測試,輸出為預測結果。

# Fit regression model
regr_1 = DecisionTreeRegressor(max_depth=2) #最大深度為2的決策樹
regr_2 = DecisionTreeRegressor(max_depth=5) #最大深度為5的決策樹
regr_3 = DecisionTreeRegressor(max_depth=8) #最大深度為8的決策樹
regr_1.fit(X, y)
regr_2.fit(X, y)
regr_3.fit(X, y)

# Predict
X_test = np.arange(-100.0, 100.0, 0.01)[:, np.newaxis]
y_1 = regr_1.predict(X_test)
y_2 = regr_2.predict(X_test)
y_3 = regr_3.predict(X_test)

(三) 繪出預測結果與實際目標圖

  • plt.scatter(X,y):將X、y以點的方式繪製於平面上,c為數據點的顏色,s決定點的大小,label為圖例。

plt.figure()
s = 50
plt.scatter(y[:, 0], y[:, 1], c="navy", s=s, label="data")
plt.scatter(y_1[:, 0], y_1[:, 1], c="cornflowerblue", s=s, label="max_depth=2")
plt.scatter(y_2[:, 0], y_2[:, 1], c="c", s=s, label="max_depth=5")
plt.scatter(y_3[:, 0], y_3[:, 1], c="orange", s=s, label="max_depth=8")
plt.xlim([-6, 6]) #設定x軸的上下限
plt.ylim([-6, 6]) #設定y軸的上下限
plt.xlabel("target 1") #x軸代表target 1數值
plt.ylabel("target 2") #x軸代表target 2數值
plt.title("Multi-output Decision Tree Regression") #標示圖片的標題
plt.legend() #繪出圖例
plt.show()

(四)完整程式碼

print(__doc__)

import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeRegressor

# Create a random dataset
rng = np.random.RandomState(1)
X = np.sort(200 * rng.rand(100, 1) - 100, axis=0)
y = np.array([np.pi * np.sin(X).ravel(), np.pi * np.cos(X).ravel()]).T
y[::5, :] += (0.5 - rng.rand(20, 2))

# Fit regression model
regr_1 = DecisionTreeRegressor(max_depth=2)
regr_2 = DecisionTreeRegressor(max_depth=5)
regr_3 = DecisionTreeRegressor(max_depth=8)
regr_1.fit(X, y)
regr_2.fit(X, y)
regr_3.fit(X, y)

# Predict
X_test = np.arange(-100.0, 100.0, 0.01)[:, np.newaxis]
y_1 = regr_1.predict(X_test)
y_2 = regr_2.predict(X_test)
y_3 = regr_3.predict(X_test)

# Plot the results
plt.figure()
s = 50
plt.scatter(y[:, 0], y[:, 1], c="navy", s=s, label="data")
plt.scatter(y_1[:, 0], y_1[:, 1], c="cornflowerblue", s=s, label="max_depth=2")
plt.scatter(y_2[:, 0], y_2[:, 1], c="c", s=s, label="max_depth=5")
plt.scatter(y_3[:, 0], y_3[:, 1], c="orange", s=s, label="max_depth=8")
plt.xlim([-6, 6])
plt.ylim([-6, 6])
plt.xlabel("target 1")
plt.ylabel("target 2")
plt.title("Multi-output Decision Tree Regression")
plt.legend()
plt.show()
http://scikit-learn.org/stable/auto_examples/tree/plot_tree_regression_multioutput.html#sphx-glr-auto-examples-tree-plot-tree-regression-multioutput-py