目录
1 样本数据
x = np.random.uniform(-5, 5, size = 100)
X = x.reshape(-1, 1)
y = 0.25*x**2 + x + 1 + np.random.normal(0, 1, 100)
plt.scatter(x, y)
plt.show()
2 线性拟合
from sklearn.linear_model import LinearRegression
linear_re = LinearRegression().fit(X, y)
y_predict = linear_re.predict(X)
plt.scatter(x,y)
plt.plot(x, y_predict, color = 'red')
plt.show()
3 二次项拟合
from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(degree = 2).fit(X)
X2 = poly.transform(X)
linear_two = LinearRegression().fit(X2, y)
y_predict_two = linear_two.predict(X2)
plt.scatter(x,y)
plt.plot(x, y_predict_two, color = 'red')
plt.show()
把x排序,且用其序列找到对应的y
4 添加一个特征一次线性拟合
X3 = np.hstack([X, X**2])
linear_three = LinearRegression().fit(X3, y)
y_predict_three = linear_three.predict(X3)
plt.scatter(x,y)
plt.plot(np.sort(x), y_predict_three[np.argsort(x)], color = 'red')
plt.show()
5 随机采样一致性ransac
from sklearn import linear_model
# Robustly fit linear model with RANSAC algorithm
X4 = np.hstack([X, X**2])
ransac = linear_model.RANSACRegressor()
ransac.fit(X4, y)
inlier_mask = ransac.inlier_mask_
outlier_mask = np.logical_not(inlier_mask)
# Predict data of estimated models
line_y_ransac = ransac.predict(X4)
plt.scatter(x, y, label= 'sampled points')
plt.plot(x, y_predict, color = 'red', label='Linear regressor')
plt.plot(np.sort(x), y_predict_two[np.argsort(x)], color = 'blue', label='Two regressor')
plt.plot(np.sort(x),line_y_ransac[np.argsort(x)], color = 'red', label='RANSAC regressor')
plt.legend(loc='lower right')
plt.xlabel("Input")
plt.ylabel("Response")
plt.show()