簡體   English   中英

AttributeError:“str”對象沒有屬性“predict”

[英]AttributeError: 'str' object has no attribute 'predict'

我正在嘗試使用 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'。

如何解決此錯誤

model = joblib.load('final_pickle_model.pkl')
model ='final_pickle_model.pkl'

您的model變量似乎被重新定義為str 這就是發生錯誤的原因,也許你可以給這個model取另一個名字?

我想你的問題在這里:

model = joblib.load('final_pickle_model.pkl') <-- looks correct
model ='final_pickle_model.pkl' <-- looks out of place (probably a mistake?)

您已將model定義為一個簡單的字符串,顯然字符串沒有predict()方法。

看我不知道如何解決它,但我認為錯誤是'str'(字符串模塊)沒有預定義的函數'predict',所以函數'predict'不能與字符串變量一起使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM