【问题标题】:saving polynomial model , doesn't save polynomial degree保存多项式模型,不保存多项式次数
【发布时间】:2020-11-12 23:18:56
【问题描述】:

当我想保存多项式模型时如何处理多项式次数,因为没有保存此信息!

import pandas as pd
import numpy as np
import joblib
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

df = pd.DataFrame({
        "a": np.random.uniform(0.0, 1.0, 1000),
        "b": np.random.uniform(10.0, 14.0, 1000),
        "c": np.random.uniform(100.0, 1000.0, 1000)})



def data():
    X_train, X_val, y_train, y_val  = train_test_split(df.iloc[:, :2].values,
                                                       df.iloc[:, 2].values,
                                                       test_size=0.2,
                                                       random_state=1340)
       
    return X_train, X_val, y_train, y_val


X_train, X_val, y_train, y_val = data()


poly_reg = PolynomialFeatures(degree = 2)
X_poly = poly_reg.fit_transform(X_train)

poly_reg_model = LinearRegression().fit(X_poly, y_train)



poly_model = joblib.dump(poly_reg_model, 'themodel')

y_pred = poly_reg_model.predict(poly_reg.fit_transform(X_val))

themodel = joblib.load('themodel')

现在,如果我尝试预测:

themodel.predict(X_val),我正在接收:

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 6 is different from 2)

我必须做的:

pol_feat = PolynomialFeatures(degree=2) themodel.predict(pol_feat.fit_transform(X_val))

为了工作。 那么,我如何存储这些信息以便能够使用模型进行预测?

【问题讨论】:

    标签: python-3.x machine-learning scikit-learn


    【解决方案1】:

    您还必须腌制训练有素的多项式特征:

    # train and pickle
    poly_reg = PolynomialFeatures(degree = 2)
    X_poly = poly_reg.fit_transform(X_train)
    poly_reg_model = LinearRegression().fit(X_poly, y_train)
    
    joblib.dump(poly_reg_model, 'themodel')
    joblib.dump(poly_reg, 'poilynomia_features_model')
    
    # load and predict
    poilynomia_features_model = joblib.load('poilynomia_features_model')
    themodel = joblib.load('themodel')
    
    X_val_prep = poilynomia_features_model.transform(X_val)
    predictions = themodel.predict(X_val_prep)
    

    但最好将所有步骤包含在单个 pipeline 中:

    pipeline = Pipeline(steps=[('poilynomia', PolynomialFeatures()), 
                               ('lr', LinearRegression())])
    
    pipeline.fit(X_train, y_train)
    pipeline.predict(X_val)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2017-11-03
      • 2021-12-31
      • 1970-01-01
      • 2017-06-16
      • 1970-01-01
      相关资源
      最近更新 更多