多项式回归-测试代码

215次阅读
没有评论
import numpy as np
import random
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt


def myfun(x):

    """
    定义一个多项式函数
    :param x: 自变量
    :return:
    """
    return 10 + 5 * x + 4 * x**2 + 6 * x**3
x = np.linspace(-3,3,7)
# 生成从 - 3 到 3 的一个 np 数组,数量为 7
print(f"x:{x}")
y = myfun(x) + np.random.random(size=len(x)) * 100 -50
# random 语法:这句话生成 [0, 1) 范围内的随机浮点数,size=len(x) 可以确保生成个数与 x 相同
print(f"y:{y}")  # 根据 x 模拟生成对应的 y
# 此时,x,y 对应真实值


featurizer_3 = PolynomialFeatures(degree=3)
x_3 = featurizer_3.fit_transform(x.reshape(-1,1))
# 用 x - 3 来储存 x 的多项式特征

model_3 = LinearRegression()
model_3.fit(x_3, y)  # 转换后的 x 特征 x_3, 来拟合原始的 y 值
# print("Model coefficients:", model_3.coef_)
# print("Model intercept:", model_3.intercept_)

x_p = (np.linspace(-2.5,2.5,100)).reshape(-1,1)
# 将这个一维数组转换为一个二维数组(矩阵)# 再生成 100 个 x 点用于模拟
x_p_3 = featurizer_3.transform(x_p)
# 用 x_p_3 来储存 x_p 的多项式特征

# 绘图
plt.figure(figsize=(10, 6))
plt.scatter(x, y, color='blue', label='Original Data')
plt.plot(x_p, myfun(x_p), color='green', label='True Function')
plt.plot(x_p, model_3.predict(x_p_3), color='red',
         label='Fitted Polynomial')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Polynomial Regression')
plt.legend()
plt.grid(True)
plt.show()
正文完
 0
评论(没有评论)