python - 从 RANSAC 回归中提取系数

标签 python math scikit-learn regression

我的代码片段取自 here 。我未能做的是从预测数据中提取参数。即对于三次函数,我想从 ax^3 + bx^2 + cx + d 方程中知道 a、b、c 和 d。如何在管道中完成此操作,特别是对于 RANSAC 估计器?

from matplotlib import pyplot as plt
import numpy as np

from sklearn.linear_model import (
    LinearRegression,
    TheilSenRegressor,
    RANSACRegressor,
    HuberRegressor,
)
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline

np.random.seed(42)

X = np.random.normal(size=400)
y = np.sin(X)
# Make sure that it X is 2D
X = X[:, np.newaxis]

X_test = np.random.normal(size=200)
y_test = np.sin(X_test)
X_test = X_test[:, np.newaxis]

y_errors = y.copy()
y_errors[::3] = 3

X_errors = X.copy()
X_errors[::3] = 3

y_errors_large = y.copy()
y_errors_large[::3] = 10

X_errors_large = X.copy()
X_errors_large[::3] = 10

estimators = [
    ("OLS", LinearRegression()),
    ("Theil-Sen", TheilSenRegressor(random_state=42)),
    ("RANSAC", RANSACRegressor(random_state=42)),
    ("HuberRegressor", HuberRegressor()),
]
colors = {
    "OLS": "turquoise",
    "Theil-Sen": "gold",
    "RANSAC": "lightgreen",
    "HuberRegressor": "black",
}
linestyle = {"OLS": "-", "Theil-Sen": "-.", "RANSAC": "--", "HuberRegressor": "--"}
lw = 3

x_plot = np.linspace(X.min(), X.max())
for title, this_X, this_y in [
    ("Modeling Errors Only", X, y),
    ("Corrupt X, Small Deviants", X_errors, y),
    ("Corrupt y, Small Deviants", X, y_errors),
    ("Corrupt X, Large Deviants", X_errors_large, y),
    ("Corrupt y, Large Deviants", X, y_errors_large),
]:
    plt.figure(figsize=(5, 4))
    plt.plot(this_X[:, 0], this_y, "b+")

    for name, estimator in estimators:
        model = make_pipeline(PolynomialFeatures(3), estimator)
        model.fit(this_X, this_y)
        mse = mean_squared_error(model.predict(X_test), y_test)
        y_plot = model.predict(x_plot[:, np.newaxis])
        plt.plot(
            x_plot,
            y_plot,
            color=colors[name],
            linestyle=linestyle[name],
            linewidth=lw,
            label="%s: error = %.3f" % (name, mse),
        )

    legend_title = "Error of Mean\nAbsolute Deviation\nto Non-corrupt Data"
    legend = plt.legend(
        loc="upper right", frameon=False, title=legend_title, prop=dict(size="x-small")
    )
    plt.xlim(-4, 10.2)
    plt.ylim(-2, 10.2)
    plt.title(title)
plt.show()

最佳答案

在我看来,在安装管道后,您可能需要在第二个 for 循环中插入类似于下面代码片段的内容:

if name == 'RANSAC':
    print(model.named_steps['ransacregressor'].estimator_.coef_)
    print(model.named_steps['ransacregressor'].estimator_.intercept_)

确实,根据documentation :

estimator_ : object

Best fitted model (copy of the base_estimator object).

因此,您需要输入所需的管道步骤(named_steps['step_name'] 是一种实现方法),然后访问 的学习系数估计器_.

关于python - 从 RANSAC 回归中提取系数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70362132/

相关文章:

用于将 PDF 转换为文本的 Python 模块

python - 为什么我的格式化程序函数接收索引而不是轴值?

matlab公式优化: Radial Basis Function

python - python中的莱文森算法

c# - 一组超过 2 个整数的最大公约数

python - 属性错误: 'numpy.ndarray' object has no attribute 'lower' fitting logistic model data

python - 是否可以使用 make_blobs 定义中心坐标?

python - 如何使用 TfIdfVectorizer 查找重要单词?

python - 如何在Python中将ndarray数组列表转换为列表

python - 将 Pandas 中的行合并为一长行