【发布时间】:2022-07-05 18:54:47
【问题描述】:
我正在尝试使用 Flask 部署基于 NLP 的垃圾邮件检测模型。 下面是我的 app.py 代码
import numpy as np
import pandas as pd
import nltk
import re
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('wordnet')
from nltk.corpus import stopwords
stop_words=stopwords.words('english')
#词形还原
from nltk.stem import WordNetLemmatizer
lemmatizer=WordNetLemmatizer()
from flask import Flask,request,jsonify,render_template,escape
import pickle
import joblib
model = joblib.load('final_pickle_model.pkl')
model ='final_pickle_model.pkl'
app=Flask(__name__,template_folder='template')
@app.route('/')
def home():
return render_template('index.html')
@app.route('/prediction')
def prediction():
return render_template('prediction.html')
@app.route('/prediction',methods=[ 'POST'])
def predict():
'''
For rendering results on HTML GUI
'''
int_features=[str(x) for x in request.form.values()]
a=int_features
msg=str(a)
filter_sentence=''
sentence=re.sub(r'[^\w\s]','',msg) #cleaning
words=nltk.word_tokenize(sentence)#tokenize
words=[w for w in words if not w in stop_words]
for word in words:
filter_sentence=filter_sentence + ' ' +str(lemmatizer.lemmatize(word)).lower()
data=(filter_sentence)
print(data)
my_prediction=model.predict(data)
my_prediction=int(my_prediction)
print(my_prediction)
if my_prediction==1:
print("This tweet is real")
return render_template('prediction.html',prediction_text="This tweet is real")
else:
print("This tweet is spam")
return render_template('prediction.html', prediction_text="This tweet is spam")
if __name__=="__main__":
app.run(debug=True)
如果我只运行我的 ML 模型,它可以完美运行而不会出错。但是当我使用烧瓶(上面的代码)部署它并输入文本并按下预测按钮时,我收到以下错误:- AttributeError: 'str' 对象没有属性 'predict'。
如何解决这个错误
【问题讨论】:
-
你问错问题了。它应该是“为什么我在这里有一个
str,我的代码需要一个predict()成员?”作为这里的新用户,也请使用tour 并阅读How to Ask。此外,确保提取并提供minimal reproducible example,包括它产生的输出。你的问题特别缺乏回溯。 -
你可以尝试格式化你的格式
predict功能更好,很难阅读