简体   繁体   中英

AttributeError: 'str' object has no attribute 'predict'

I am trying to deploy my NLP based spam detection model using Flask. Below is my app.py code

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')

#Lemmatization

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)

If I run only my ML model, it runs perfectly without error. But when I deploy it using flask (above code), and enter the text and press predict button, I get following error:- AttributeError: 'str' object has no attribute 'predict'.

How to solve this error

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

It seems that your model variable is redefined as str . And this is why the error is occured, maybe you can get this model another name?

I imagine your problem is here:

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

You have defined model to be a simple string and obviously a string doesn't have a predict() method.

看我不知道如何解决它,但我认为错误是'str'(字符串模块)没有预定义的函数'predict',所以函数'predict'不能与字符串变量一起使用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM