import numpy as np
import matplotlib.pyplot as plt
import mglearn
from sklearn.preprocessing import OneHotEncoder
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.tree import export_graphviz
x,y = mglearn.datasets.make_wave(n_samples=100)
line = np.linspace(-3,3,1000,endpoint=False).reshape(-1,1)
bins = np.linspace(-3,3,11)
which_bin = np.digitize(x,bins=bins)
encoder = OneHotEncoder(sparse=False)
print(which_bin.shape)
encoder.fit(which_bin)
x_binned = encoder.transform(which_bin)
line_binned = encoder.transform(np.digitize(line,bins=bins))
lin = LinearRegression().fit(x_binned,y)
plt.plot(line,lin.predict(line_binned),label='Liner regression')
tree = DecisionTreeRegressor(min_samples_split=3).fit(x_binned,y)
plt.plot(line,tree.predict(line_binned),label = 'tree regression')
x_combined = np.hstack([x,x_binned])
print(x_combined.shape)
reg = LinearRegression().fit(x_combined,y)
line_combined = np.hstack([line,line_binned])
plt.plot(x_combined[:,0],reg.predict(x_combined),'^',label='x_combined')
plt.plot(x[:,0],y,'o')
plt.legend()
plt.vlines(bins,-3,3)
plt.show()
为什么每个箱子的斜率都是相同的?
最新推荐文章于 2022-03-20 09:25:17 发布