多项式回归处理非线性问题

参考资料:多项式回归处理非线性问题

多项式回归是一种通过增加自变量上的次数,而将数据映射到高维空间的方法,从而提高模型拟合复杂数据的效果。

线性模型中的升维工具----多项式变化。是一种通过增加自变量上的次数,而将数据映射到高维空间的方法,在sklearn中的PolynomialFeatures 设定一个自变量上的次数(大于1),相应地获得数据投影在高次方的空间中的结果。

语法:

sklearn.preprocessing.PolynomialFeatures (degree=2, interaction_only=False, include_bias=True)

重要参数:

degree : integer
多项式中的次数,默认为2
interaction_only : boolean, default = False
布尔值是否只产生交互项,默认为False。就只能将原有的特征进行组合出新的特征,而不能直接对原特征进行升次。
include_bias : boolean
布尔值,是否产出与截距项相乘的 ,默认True

案例一、拟合正弦曲线

线性回归模型无法拟合出这条带噪音的正弦曲线的真实面貌,只能够模拟出大概的趋势,而用复杂的决策树模型又拟合地太过细致,即过拟合。此时利用多项式将数据升维,并拟合数据

在这里插入图片描述

案例二、不同的最高次取值对拟合效果的影响

在这里插入图片描述

案例三、利用pipeline将三个模型封装起来串联操作

在这里插入图片描述

完整代码:

https://github.com/SeafyLiang/machine_learning_study/blob/master/regression/polynomialFeatures.py

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures as PF, StandardScaler
from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt


def demo1():
    '''
    利用多项式将数据升维,并拟合数据
    '''
    rnd = np.random.RandomState(42)  # 设置随机数种子
    X = rnd.uniform(-3, 3, size=100)
    y = np.sin(X) + rnd.normal(size=len(X)) / 3
    # 将X升维,准备好放入sklearn中
    X = X.reshape(-1, 1)
    # 多项式拟合,设定高次项
    d = 5
    # 原始特征矩阵的拟合结果
    LinearR = LinearRegression().fit(X, y)
    # 进行高此项转换
    X_ = PF(degree=d).fit_transform(X)
    LinearR_ = LinearRegression().fit(X_, y)
    line = np.linspace(-3, 3, 1000, endpoint=False).reshape(-1, 1)
    line_ = PF(degree=d).fit_transform(line)
    # 放置画布
    fig, ax1 = plt.subplots(1)
    # 将测试数据带入predict接口,获得模型的拟合效果并进行绘制
    ax1.plot(line, LinearR.predict(line), linewidth=2, color='green'
             , label="linear regression")
    ax1.plot(line, LinearR_.predict(line_), linewidth=2, color='orange'
             , label="Polynomial regression")  # 将原数据上的拟合绘制在图像上
    ax1.plot(X[:, 0], y, 'o', c='k')
    # 其他图形选项
    ax1.legend(loc="best")
    ax1.set_ylabel("Regression output")
    ax1.set_xlabel("Input feature")
    ax1.set_title("Linear Regression ordinary vs poly")
    ax1.text(0.8, -1, f"LinearRegression score:\n{LinearR.score(X, y)}", fontsize=15)
    ax1.text(0.8, -1.3, f"LinearRegression score after poly :\n{LinearR_.score(X_, y)}", fontsize=15)

    plt.tight_layout()
    plt.show()


# 生产数据函数
def uniform(size):
    x = np.linspace(0, 1, size)
    return x.reshape(size, 1)


def create_data(size):
    x = uniform(size)
    np.random.seed(42)  # 设置随机数种子
    y = sin_fun(x) + np.random.normal(scale=0.25, size=x.shape)
    return x, y


def sin_fun(x):
    return np.sin(2 * np.pi * x)


def demo2():
    '''
    不同的最高次取值,对模型拟合效果有重要的影响。
    '''
    X_train, y_train = create_data(20)
    X_test = uniform(200)
    y_test = sin_fun(X_test)
    fig = plt.figure(figsize=(12, 8))
    for i, degree in enumerate([0, 1, 3, 6, 9, 12]):
        plt.subplot(2, 3, i + 1)

        poly = PF(degree)
        X_train_ploy = poly.fit_transform(X_train)
        X_test_ploy = poly.fit_transform(X_test)

        lr = LinearRegression()
        lr.fit(X_train_ploy, y_train)
        y_pred = lr.predict(X_test_ploy)

        plt.scatter(X_train, y_train, facecolor="none", edgecolor="g", s=25, label="training data")
        plt.plot(X_test, y_pred, c="orange", label="fitting")
        plt.plot(X_test, y_test, c="k", label="$\sin(2\pi x)$")
        plt.title("N={}".format(degree))
        plt.legend(loc="best")
        plt.ylabel("Regression output")
        #     plt.xlabel("Input feature")
        plt.legend()
    plt.show()


def demo3():
    '''
    利用pipeline将三个模型封装起来串联操作,让模型接口更加简洁,使用起来方便
    '''
    X, y = create_data(200)  # 利用上面的生产数据函数
    degree = 6
    # 利用Pipeline将三个模型封装起来串联操作n
    poly_reg = Pipeline([
        ("poly", PF(degree=degree)),
        ("std_scaler", StandardScaler()),
        ("lin_reg", LinearRegression())
    ])
    fig = plt.figure(figsize=(10, 6))
    poly = PF(degree)
    poly_reg.fit(X, y)
    y_pred = poly_reg.predict(X)
    # 可视化结果
    plt.scatter(X, y, facecolor="none", edgecolor="g", s=25, label="training data")
    plt.plot(X, y_pred, c="orange", label="fitting")
    # plt.plot(X,y,c="k",label="$\sin(2\pi x)$")
    plt.title("degree={}".format(degree))
    plt.legend(loc="best")
    plt.ylabel("Regression output")
    plt.xlabel("Input feature")
    plt.legend()
    plt.show()


if __name__ == '__main__':
    demo1()
    demo2()
    demo3()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值