首页 > 解决方案 > 错误:列表索引必须是整数或切片,而不是列表 - 在烧瓶中部署管道模型时

问题描述

我正在尝试部署使用 Pipeline 生成的模型。它在 jupyter 或 spyder 笔记本上运行良好。但是,在部署即时消息时,出现以下错误: 列表索引必须是整数或切片,而不是列表

这是导入库后我的 app.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 ] 
pass


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['Monthly Premium Auto'] = np.log(X['Monthly Premium Auto'])
    return X.values
pass

传递为管道创建的函数

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 = [int(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__":  

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

    print("loaded OK")

    app.run(debug=True)

很长一段时间以来,我一直在努力寻找解决方案。任何帮助都会很棒。谢谢你。

标签: pythonlistmachine-learningflaskpipeline

解决方案


我通过将输出转换为 pandas DataFrame 解决了这个错误。这有助于解决我的模型在格式和数据类型方面面临的所有错误。Simple 将输入数据更改为数据框。


推荐阅读