版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/alionsss/article/details/87635685
多项式回归示例(sklearn实现)
1. 导包
import numpy as np
import matplotlib. pyplot as plt
from sklearn. preprocessing import PolynomialFeatures
from sklearn. linear_model import LinearRegression
2. 原始数据生成与展示
x_data = np. array( [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] )
y_data = np. array( [ 45 , 55 , 60 , 85 , 115 , 140 , 222 , 350 , 600 , 1000 ] )
plt. scatter( x_data, y_data)
plt. show( )
3. 数据预处理
x_data = x_data[ : , np. newaxis]
y_data = y_data[ : , np. newaxis]
poly_reg = PolynomialFeatures( degree= 3 )
x_data_poly = poly_reg. fit_transform( x_data)
4. 建立模型,开始训练
model = LinearRegression( )
model. fit( x_data_poly, y_data)
5. 预测结果与展示
x_test = np. linspace( 1 , 10 , 50 ) [ : , np. newaxis]
x_test_poly = poly_reg. fit_transform( x_test)
predict_result = model. predict( x_test_poly)
print ( predict_result)
plt. plot( x_data, y_data, "b." )
plt. plot( x_test, predict_result, c= "r" )
plt. show( )