You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Sklearn拟合含(1-x²)^(1/2)项的复杂函数?

可以用Sklearn实现这类自定义特征的拟合

Sklearn的PolynomialFeatures仅能生成多项式项,但你可以通过手动构造自定义特征并与多项式特征合并的方式,实现包含(1-x²)^(1/2)项的拟合。以下是具体实现方案:

方法一:手动构造并合并特征

这种方式直接明了,适合快速验证:

import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

# 假设你的输入数据
xvalues = np.linspace(-0.9, 0.9, 100)  # 注意:x必须在[-1,1]范围内,避免根号内为负
y_values = 0.5 * xvalues**2 + 0.8 * np.sqrt(1 - xvalues**2) + np.random.normal(0, 0.05, 100)

# 1. 生成多项式特征(x, x²)
poly = PolynomialFeatures(degree=2, include_bias=False)
poly_features = poly.fit_transform(xvalues.reshape(-1, 1))

# 2. 生成自定义特征:sqrt(1-x²),必须转为2D数组(符合Sklearn输入要求)
custom_feature = np.sqrt(1 - xvalues**2).reshape(-1, 1)

# 3. 合并多项式特征与自定义特征
combined_features = np.hstack([poly_features, custom_feature])

# 4. 拟合线性回归模型
poly_reg_model = LinearRegression()
poly_reg_model.fit(combined_features, y_values)
final_predicted = poly_reg_model.predict(combined_features)

方法二:用Sklearn Pipeline标准化流程

如果需要更规范的特征工程流程(比如后续要做交叉验证、模型部署),推荐使用Pipeline结合FunctionTransformer:

import numpy as np
from sklearn.preprocessing import PolynomialFeatures, FunctionTransformer
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer

# 定义生成自定义特征的函数
def generate_custom_feature(x):
    return np.sqrt(1 - x**2).reshape(-1, 1)

# 构建特征预处理管道:同时生成多项式特征和自定义特征
preprocessor = ColumnTransformer(
    transformers=[
        # 处理多项式特征
        ("poly_features", PolynomialFeatures(degree=2, include_bias=False), [0]),
        # 处理自定义特征
        ("custom_feature", FunctionTransformer(generate_custom_feature), [0])
    ]
)

# 整合整个建模流程
model_pipeline = Pipeline([
    ("preprocess", preprocessor),
    ("regressor", LinearRegression())
])

# 拟合模型(输入需为2D数组)
x_2d = xvalues.reshape(-1, 1)
model_pipeline.fit(x_2d, y_values)
final_predicted = model_pipeline.predict(x_2d)

你之前尝试失败的可能原因

  • 自定义特征未转换为二维数组:Sklearn的所有特征输入要求是(样本数, 特征数)的二维格式,一维数组会导致维度不匹配。
  • 未处理x的范围:如果x超出[-1,1],sqrt(1-x²)会产生NaN或复数,导致拟合失败。

内容的提问来源于stack exchange,提问作者Olaf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 05:30:42