Skip to content

Instantly share code, notes, and snippets.

@tianhuil
Created January 1, 2014 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tianhuil/8209488 to your computer and use it in GitHub Desktop.
Save tianhuil/8209488 to your computer and use it in GitHub Desktop.
Decision tree versus linear regression comparison plot
import numpy as np
# Create a random dataset
rng = np.random.RandomState(1)
X = np.sort(5 * rng.rand(80, 1), axis=0)
y = np.sin(X).ravel()
y += .2 * (0.5 - rng.rand(80))
# Fit regression model
from sklearn.tree import DecisionTreeRegressor
from sklearn.linear_model import LinearRegression
clf_1 = DecisionTreeRegressor(max_depth=4)
clf_2 = LinearRegression()
clf_1.fit(X, y)
clf_2.fit(X, y)
# Predict
X_test = np.arange(0.0, 5.0, 0.01)[:, np.newaxis]
y_1 = clf_1.predict(X_test)
y_2 = clf_2.predict(X_test)
# Plot the results
import pylab as pl
pl.figure()
pl.scatter(X, y, c="k", label="data")
pl.plot(X_test, y_1, c="g", label="Decision Tree", linewidth=2)
pl.plot(X_test, y_2, c="r", label="Linear Regresison", linewidth=2)
pl.xlabel("data")
pl.ylabel("target")
pl.title("Decision Tree versus Linear Regression")
pl.legend()
pl.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment