【问题标题】:Get the coefficients of my sklearn polynomial regression model in Python在 Python 中获取我的 sklearn 多项式回归模型的系数
【发布时间】:2018-10-23 08:30:58
【问题描述】:

我想在 Python 中获得我的 sklearn 多项式回归模型的系数,这样我就可以在其他地方写出等式......即 ax1^2 + ax + bx2^2 + bx2 + c

我在其他地方查看了答案,但似乎无法找到解决方案,除非我只是不知道自己在看什么。

from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 2)
X_poly = poly_reg.fit_transform(X_train)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly,y_train)

lin_reg_2.coef_

【问题讨论】:

标签: python scikit-learn


【解决方案1】:

支持向量回归:

from sklearn.svm import SVR
import numpy as np
n_samples, n_features = 10, 5
np.random.seed(0)
y = np.random.randn(n_samples)
X = np.random.randn(n_samples, n_features)
clf = SVR(kernel="poly",degree=3,gamma="scale",C=0.8)
clf.fit(X, y) 
clf.predict(X)

sklearn.svm.SVR类定义:

class sklearn.svm.SVR(kernel=’rbf’, degree=3, gamma=’auto_deprecated’, coef0=0.0, tol=0.001, C=1.0, epsilon=0.1, shrinking=True, cache_size=200, verbose=False, max_iter=-1)

【讨论】:

    【解决方案2】:

    这个 sn-p 应该可以工作,它取自我自己的脚本:

    from sklearn.linear_model import LinearRegression
    from sklearn.preprocessing import PolynomialFeatures
    poly_reg = PolynomialFeatures(degree=2)
    poly_x_inliers = poly_reg.fit_transform(x_inliers)
    
    regressor = LinearRegression()
    regressor.fit(poly_x_inliers, y_inliers)
    
    reg_label = "Inliers coef:%s - b:%0.2f" % \
                (np.array2string(regressor.coef_,
                                 formatter={'float_kind': lambda fk: "%.3f" % fk}),
                regressor.intercept_)
    print(reg_label)
    

    您应该查看:https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html

    【讨论】:

      【解决方案3】:

      你离得太近了。问题是你如何编写模型。为了让它工作,你必须把它写成:

      from sklearn.linear_model import LinearRegression
      from sklearn.preprocessing import PolynomialFeatures
      poly_reg = PolynomialFeatures(degree = 2)
      X_poly = poly_reg.fit_transform(X_Train)
      lin_reg_2=LinearRegression().fit(X_poly, y_Train)
      pred = lin_reg_2.predict(X_poly_test) #this line is not necessary. It's just a predict for test data
      
      lin_reg_2.coef_
      

      还要确保 X_train 和 y_train 是具有正确形状的数组。

      【讨论】:

        猜你喜欢
        • 2017-04-06
        • 2018-12-25
        • 1970-01-01
        • 2020-01-14
        • 1970-01-01
        • 2019-12-20
        • 2019-06-07
        • 1970-01-01
        • 2015-06-10
        相关资源
        最近更新 更多