【问题标题】:Pipeline deployment in Flask (python)Flask 中的管道部署(python)
【发布时间】:2020-06-03 16:02:54
【问题描述】:

我正在尝试通过 Flask 部署使用 Pipeline 构建的模型,但是我面临以下属性错误 '无法从'app.py'获取属性'FeatureSelector' on main''

这是我的 model.py 代码: (加载必要的库并读取数据后,我已经为我的管道定义了类)

class FeatureSelector( BaseEstimator, TransformerMixin ):
#Class Constructor 
def __init__( self, feature_names ):
    self._feature_names = feature_names 

#Return self nothing else to do here    
def fit( self, X, y =None):
    return self 

#Method that describes what we need this transformer to do
def transform( self, X, y = None):
    return X[ self._feature_names ] 

LE = LabelEncoder()
class CategoricalTransformer( BaseEstimator, TransformerMixin ):
#Class constructor method that takes in a list of values as its argument
def __init__(self, cat_cols = ['Response', 'EmploymentStatus', 'Number of Open Complaints',
   'Number of Policies', 'Policy Type', 'Renew Offer Type',
   'Vehicle Class']):
    self._cat_cols = cat_cols

#Return self nothing else to do here
def fit( self, X, y = None  ):
    return self

#Transformer method we wrote for this transformer 
def transform(self, X , y = None ):

   if self._cat_cols:
    for i in X[cat_cols]:
        X[i]= LE.fit_transform(X[i])

   return X.values 

class NumericalTransformer(BaseEstimator, TransformerMixin):
#Class Constructor
def __init__( self, MPA_log = True):
    self._MPA_log = MPA_log

#Return self, nothing else to do here
def fit( self, X, y = None):
    return self 

#Custom transform method we wrote that creates aformentioned features and drops redundant ones 
def transform(self, X, y = None):
    if self._MPA_log:
        X.loc[:,'MPA_log'] = np.log(X['Monthly Premium Auto'])
        X.drop(['Monthly Premium Auto'], axis =1)

    return X.values

我为数字和分类事件创建了不同的管道。它们已在 Full Pipeline 中使用 Feture Union 进行组合。

   full_pipeline = FeatureUnion( transformer_list = [ ( 'categorical_pipeline', categorical_pipeline ), ( 'numerical_pipeline', numerical_pipeline ) ] )

   X = df.drop('Customer Lifetime Value', axis = 1)
   y = df['Customer Lifetime Value']

   y = np.log(y) #Transforming the y variable

  full_pipeline_RF = Pipeline( steps = [('full_pipeline', full_pipeline),('model', 
  RandomForestRegressor(max_depth=21, min_samples_leaf= 8, random_state=0))])
  full_pipeline_RF.fit(X, y)


  # Saving model to disk
  pickle.dump(full_pipeline_RF, open('model.pkl','wb'))

  # Loading model to compare the results
  model = pickle.load(open('model.pkl','rb'))

模型已在 app.py 文件中调用,代码如下:

import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle

app = Flask(__name__)
model = pickle.load(open('model.pkl', 'rb'))

@app.route('/')
def home():
return render_template('index.html')

@app.route('/predict',methods=['POST'])
def predict():
'''
For rendering results on HTML GUI
'''
int_features = [float(x) for x in request.form.values()]
final_features = [np.array(int_features)]
prediction = model.predict(final_features)

output = round(np.exp(prediction[0]),2)


return render_template('index.html', prediction_text='Customer Lifetime Value $ {}'.format(output))


if __name__ == "__main__":
app.run(debug=True)

代码在 Jupyter 中运行良好。即使在 Spyder 中运行,它也不会抛出任何错误。请帮我处理这段代码,我只停留在执行位上。

【问题讨论】:

    标签: machine-learning flask data-science pipeline data-modeling


    【解决方案1】:

    这其实很简单。我所要做的就是在我的 app.py 中传递在管道期间创建的类。 这些是为案例定制的新类,因此需要通过这些类。 只需在定义每个类后写上“pass”即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      • 2015-08-25
      • 2018-08-28
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多