09 非线性回归
9.1 简介
非线性回归用于处理那些数据与线性模型不适配的情况。非线性回归模型能够捕捉数据中的非线性关系,通过对特征进行非线性变换或者直接使用非线性函数来拟合模型。
9.2 多项式回归
多项式回归是最常用的非线性回归方法之一,它通过将原始特征升维(即增加特征的幂次项)来捕捉非线性关系。多项式回归依然可以被看作是线性回归的一种,只不过特征经过了非线性变换。
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# 生成模拟数据
np.random.seed(42)
X = np.random.rand(100, 1) * 10
y = 2 + 3 * X + 4 * X**2 + np.random.randn(100, 1) * 5
# 生成多项式特征
poly = PolynomialFeatures(degree=2)
X_poly = poly.fit_transform(X)
# 拆分训练集和测试集
X_trai