Home > front end >  AttributeError: 'str' object has no attribute 'predict'
AttributeError: 'str' object has no attribute 'predict'

Time:04-17

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

CodePudding user response:

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?

CodePudding user response:

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.

CodePudding user response:

Look I dont know how to fix it excatly but I think the error is that 'str' (String module) has no pre defined function 'predict' so the function 'predict' cannot be used with a String variable

  • Related