线性回归、二次回归、随机采样一致性ransac的数据拟合

目录

1 样本数据

2 线性拟合

3 二次项拟合

4 添加一个特征一次线性拟合

5 随机采样一致性ransac


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()

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值