文章目录
任务描述实现细节效果演示全部代码
任务描述
通过回归算法对正弦曲线(有噪声)进行拟合
实现细节
产生一组随机数,取值在 [0,20] 之间作为 x_train (训练数据)对 x_train 取其正弦函数为 y_由于在真正的数据集中,数据往往存在噪声,所以对 y_ 添加噪声作为 y_train (训练标签)同样的方式,我们用另外一个随机状态 randstate(3) 来产生 x_test 和 y_test 作为测试数据和测试标签使用 sklearn 库建立回归模型(可以是任何常用的回归模型:决策树回归、svm、线性回归。。。等,按照自己的喜好来即可)通过回归模型对训练数据 x_train, x_test 进行拟合用 x_test, y_test 数据来检测拟合的效果,得出评分最后我们把 x_test 输入模型,得出训练好的模型对于 x_test 数据的预测曲线,可视化拟合效果
效果演示
这是 x_train, y_train 的训练数据曲线图
这是通过回归算法拟合出的曲线,在测试集上的精确度可以达到 91%(决策树回归算法)
全部代码
import numpy
as np
import matplotlib
.pyplot
as plt
import math
'''
训练集和测试集都用随机数产生,都是80个(0,1)之间的随机数,
将他们乘以 20 让其位于(0,20)之间的随机数,作为 x 数据
'''
rgn
= np
.random
.RandomState
(1)
rgn2
= np
.random
.RandomState
(2)
rgn3
= np
.random
.RandomState
(3)
x_
= 20 * rgn
.rand
(80,1)
x_train
= np
.sort
(x_
,axis
=0)
y_
= np
.sin
(x_train
)
y_train
= 1/2 * rgn2
.rand
(80,1) + y
plt
.figure
(figsize
=(10,3))
plt
.scatter
(x
,y_noise
)
plt
.plot
(x
,y_noise
,color
='red')
plt
.show
()
from sklearn
.linear_model
import LinearRegression
from sklearn
.tree
import DecisionTreeRegressor
x_
= 20 * rgn3
.rand
(80,1)
x_test
= np
.sort
(x_
,axis
=0)
y_
= np
.sin
(x_test
)
y_test
= y_
+ 1/2 * rgn2
.rand
(80,1)
reg
= DecisionTreeRegressor
()
reg
.fit
(x
,y_noise
)
score
= reg
.score
(x_test
,y_test
)
y_predict
= reg
.predict
(x_test
)
plt
.figure
(figsize
=(10,3))
plt
.plot
(x_test
,y_test
,color
='orange',label
='x_test,y_test')
plt
.plot
(x_train
,y_train
,color
='red',label
='x_train,y_train')
plt
.plot
(x_test
,y_predict
,color
='black',label
='x_test,y_predict')
plt
.legend
()
print(score
)