我正在嘗試使用決策樹回歸進行單變數回歸。但是,當我繪制結果時。圖中顯示多條線,如下圖所示。我使用線性回歸時沒有遇到這個問題。
https://snipboard.io/v9QaoC.jpg - 我無法發布圖片,因為我的聲譽低于 10
我的代碼:
import numpy as np
from sklearn.tree import DecisionTreeRegressor
import matplotlib.pyplot as plt
# Fit regression model
regr_1 = DecisionTreeRegressor(max_depth=2)
regr_2 = DecisionTreeRegressor(max_depth=5)
regr_1.fit(X_train.values.reshape(-1, 1), y_train.values.reshape(-1, 1))
regr_2.fit(X_train.values.reshape(-1, 1), y_train.values.reshape(-1, 1))
# Predict
y_1 = regr_1.predict(X_test.values.reshape(-1, 1))
y_2 = regr_2.predict(X_test.values.reshape(-1, 1))
# Plot the results
plt.figure()
plt.scatter(X_train, y_train, s=20, edgecolor="black", c="darkorange", label="data")
plt.plot(X_test, y_1, color="cornflowerblue", label="max_depth=2", linewidth=2)
plt.plot(X_test, y_2, color="yellowgreen", label="max_depth=5", linewidth=2)
plt.xlabel("data")
plt.ylabel("target")
plt.title("Decision Tree Regression")
plt.legend()
plt.show()
uj5u.com熱心網友回復:
您的繪圖可能沒有吸引力,因為您的測驗樣本沒有排序,因此您在不同的測驗資料點之間隨機“連接點”。這對于您的線性回歸解決方案尚不清楚,因為這些線是重疊的。
您可以通過對測驗資料進行排序來獲得您期望的圖:
# Sort
X_test = np.sort(X_test) # Need to specify axis=0 if X_test has shape (n_samples, 0)
# Predict
y_1 = regr_1.predict(X_test.values.reshape(-1, 1))
y_2 = regr_2.predict(X_test.values.reshape(-1, 1))
# Plot the results
plt.figure()
plt.scatter(X_train, y_train, s=20, edgecolor="black", c="darkorange", label="data")
plt.plot(X_test, y_1, color="cornflowerblue", label="max_depth=2", linewidth=2)
plt.plot(X_test, y_2, color="yellowgreen", label="max_depth=5", linewidth=2)
plt.xlabel("data")
plt.ylabel("target")
plt.title("Decision Tree Regression")
plt.legend()
plt.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/475292.html
標籤:机器学习 scikit-学习 回归 数据可视化 决策树
下一篇:梯度下降演算法中的偏導項
