ML model error 'numpy.ndarray' object has no attribute 'predict' - python

I was trying to make a predictive model, but I can't find a way to solve this numpy-related issue with my code. I already imported the pickle file containing the model I saved from Google Colab, but I can't seem to make it work. Any type of response will be appreciated!
app.py
from flask import Flask, render_template, request
import pickle
import numpy as np
import joblib
model = pickle.load(open('model_car_price', 'rb'))
joblib.dump(model,'model_car_prices_data')
# imported the pickle file containing the ML model
realmodel = pickle.load(open('model_car_prices_data', 'rb'))
app = Flask(__name__)
app.debug = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
#app.route('/')
def man():
return render_template('home.html')
#app.route('/predict', methods=['POST'])
def home():
data1 = request.form['a']
data2 = request.form['b']
data3 = request.form['c']
data4 = request.form['d']
data5 = request.form['e']
data6 = request.form['f']
data7 = request.form['g']
arr = np.array([[data1, data2, data3, data4, data5, data6, data7]])
pred = model.predict(arr)
return render_template('after.html', data=pred)
if __name__ == "__main__":
app.run(debug=True)

Try typing
type(model)
pickle.load seems to be returning an numpy array

Related

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0), json error

from flask import Flask, request, jsonify
import joblib
app = Flask(__name__)
#app.route('/predict', methods=['POST','GET'])
def predict():
model = joblib.load('rf_grid.pkl')
data = request.get_json()
prediction = model.predict([[np.array(data['Age'],data['SipSp'],data['Parch'],
data['Fare'],data['Sex_male'],
data['Cabin_Rare'],data['Embarked_S'])]])
output = prediction[0]
return jsonify(output)
if __name__ == '__main__':
app.run(debug=True)
This is a flask file that I'm running under app.py
import requests
import json
url ='http://127.0.0.1:5000/predict'
dictionary = {'Age':50, 'SipSp':1, 'Parch':1,'Fare':150,'Sex_male':1,'Cabin_Rare':0,'Embarked_S':1}
r = requests.post(url, json = dictionary)
print(r.json())
This is the file I'm running under requests.py. When I run this file I get the error:json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
How do I get rid of this error and for my requests.py to run?
There is an error in your API logic. I have commented core logic portion and returned JSON response. And It it's not giving any error.
import numpy as np
from flask import Flask, request, jsonify
import joblib
app = Flask(__name__)
#app.route('/predict', methods=['POST','GET'])
def predict():
# model = joblib.load('rf_grid.pkl')
# data = request.get_json()
# prediction = model.predict([[np.array(data['Age'],data['SipSp'],data['Parch'],
# data['Fare'],data['Sex_male'],
# data['Cabin_Rare'],data['Embarked_S'])]])
# output = prediction[0]
output = {"ok": True}
return jsonify(output)
if __name__ == '__main__':
app.run(debug=True)
If you can please share rf_grid.pkl file So, I can help with that.

AttributeError: module 'tensorflow' has no attribute 'get_default_graph' using tf =2.4

from flask import Flask, render_template, flash, request, url_for, redirect, session
import numpy as np
import pandas as pd
import re
import os
import tensorflow as tf
from numpy import array
from keras.datasets import imdb
from keras.preprocessing import sequence
from tensorflow.keras.models import load_model
IMAGE_FOLDER = os.path.join('static', 'img_pool')
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = IMAGE_FOLDER
def init():
global model,graph
# load the pre-trained Keras model
model = load_model('sentiment_analysis_model_new.h5')
graph = tf.get_default_graph()
#########################Code for Sentiment Analysis
#app.route('/', methods=['GET', 'POST'])
def home():
return render_template("home.html")
#app.route('/sentiment_analysis_prediction', methods = ['POST', "GET"])
def sent_anly_prediction():
if request.method=='POST':
text = request.form['text']
sentiment = ''
max_review_length = 500
word_to_id = imdb.get_word_index()
strip_special_chars = re.compile("[^A-Za-z0-9 ]+")
text = text.lower().replace("<br />", " ")
text=re.sub(strip_special_chars, "", text.lower())
words = text.split() #split string into a list
x_test = [[word_to_id[word] if (word in word_to_id and word_to_id[word]<=20000) else 0 for word in words]]
x_test = sequence.pad_sequences(x_test, maxlen=500) # Should be same which you used for training data
vector = np.array([x_test.flatten()])
with graph.as_default():
probability = model.predict(array([vector][0]))[0][0]
class1 = model.predict_classes(array([vector][0]))[0][0]
if class1 == 0:
sentiment = 'Negative'
img_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'Sad_Emoji.png')
else:
sentiment = 'Positive'
img_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'Smiling_Emoji.png')
return render_template('home.html', text=text, sentiment=sentiment, probability=probability, image=img_filename)
#########################Code for Sentiment Analysis
if __name__ == "__main__":
init()
app.run(debug=True)
Trying to run above mentioned code in anaconda prompt getting -
File "app.py", line 23, in init
graph = tf.get_default_graph()
AttributeError: module 'tensorflow' has no attribute 'get_default_graph'
What I have done to solve this issue? I still get the same error:
I changed the imports from keras.something.something to tensorflow.keras.something and the issue seemed to have gone away. Putting it here for others to benefit.
I tried with installation of tf=1.14.1
Currently using tf== 2.4
How to solve this issue in this version?
Use the compatibility module
import tensorflow.compat.v1 as tf
tf.get_default_graph()

Python Flask File Upload fails with 404 error

While following the Flask documentation / tutorials on how to upload a file I used this code:
main.py:
from flask import render_template, jsonify, Flask, redirect, url_for, request
from app import app
import random
import os
from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np
#app.route('/')
#app.route('/upload')
def upload_file2():
return render_template('index.html')
#app.route('/uploaded', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
path = os.path.join(app.config['UPLOAD_FOLDER'], f.filename)
model= ResNet50(weights='imagenet')
img = image.load_img(path, target_size=(224,224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
preds_decoded = decode_predictions(preds, top=3)[0]
print(decode_predictions(preds, top=3)[0])
f.save(path)
return render_template('uploaded.html', title='Success', predictions=preds_decoded, user_image=f.filename)
#app.route('/index')
def index():
return render_template('index.html', title='Home')
#app.route('/map')
def map():
return render_template('map.html', title='Map')
#app.route('/map/refresh', methods=['POST'])
def map_refresh():
points = [(random.uniform(48.8434100, 48.8634100),
random.uniform(2.3388000, 2.3588000))
for _ in range(random.randint(2, 9))]
return jsonify({'points': points})
#app.route('/contact')
def contact():
return render_template('contact.html', title='Contact')
Everything seems to be fine in the code. I have checked several times.
Well when running it on localhost on my Windows machine.
I get an 404 http-status-code (page not found).
I tried: on http://localhost:5000/ and http://localhost:5500/
Also I cleaned my browser...
Change
#app.route('/uploaded', methods = ['GET', 'POST'])
To
#app.route('/upload.php', methods = ['GET', 'POST'])
Or, change your front end form to post to uploaded.

How to apply the Python function with predictive model into Flask application

I have a code that consists of two logical parts: receiving POST json request in Flask and function with prediction model. So here how it looks in code representation:
from flask import Flask
from flask import request
import io
import json
import pandas as pd
import numpy as np
from fbprophet import Prophet
app = Flask(__name__)
#app.route('/postjson', methods = ['POST'])
def postJsonHandler():
print (request.is_json)
content = request.get_json()
df = pd.io.json.json_normalize(content, ['Days', 'Orders'])
print (df)
return 'JSON posted'
app.run(host='0.0.0.0', port= 8090)
And here is the part with the function with model:
def TimeSeries ():
df['Days'] = pd.to_datetime(df['Days'])
df = df.rename(columns={'Days': 'ds',
'Orders': 'y'})
my_model = Prophet(interval_width=0.95, yearly_seasonality=False, daily_seasonality=False, weekly_seasonality=True)
df['y'] = np.log(df['y'])
my_model.fit(df)
future_dates = my_model.make_future_dataframe(periods=30)
forecast = my_model.predict(future_dates)
yhat=forecast.yhat
ser=np.exp(yhat)
df_upd=pd.DataFrame(ser[-30:])
df_upd.reset_index(drop=True, inplace=True)
js=df_upd.to_dict(orient='split')
del js['index']
res=json.dumps(js)
return res
My questions will bу following:
How can I transfer the result dataframe df from first part function postJsonHandler () and use it as an input in the second part function TimeSeries()?
How can I integrate my predictive function TimeSeries() in Flask environment to be able to run everything at once- to receive a json request, transform it into pandas dataframe, caluclates the result of prediction in json format and transfer this to server.
Big Thanks!
You combine your functions:
from flask import Flask
from flask import request
import io
import json
import pandas as pd
import numpy as np
from fbprophet import Prophet
app = Flask(__name__)
my_model = Prophet(interval_width=0.95, yearly_seasonality=False, daily_seasonality=False, weekly_seasonality=True)
#app.route('/postjson', methods = ['POST'])
def postJsonHandler():
print (request.is_json)
content = request.get_json()
df = pd.io.json.json_normalize(content, ['Days', 'Orders'])
df['Days'] = pd.to_datetime(df['Days'])
df = df.rename(columns={'Days': 'ds',
'Orders': 'y'})
df['y'] = np.log(df['y'])
my_model.fit(df)
future_dates = my_model.make_future_dataframe(periods=30)
forecast = my_model.predict(future_dates)
yhat=forecast.yhat
ser=np.exp(yhat)
df_upd=pd.DataFrame(ser[-30:])
df_upd.reset_index(drop=True, inplace=True)
js=df_upd.to_dict(orient='split')
del js['index']
res=json.dumps(js)
app.run(host='0.0.0.0', port= 8090

Pass variables between different scripts python

I made a script python app.py and I managed to store data from a javascript form, thanks to a flask app :
app = Flask(__name__)
app.config.from_object('config')
db.init_app(app)
#app.route('/getFormData', methods=['POST'])
def get_javascript_data():
params = request.form.to_dict()
sunElevation = params['sunElevation']
cloudCoverage = params['cloudCoverage']
thresholdNDVI = params['thresholdNDVI']
limitScene = params['limitScene']
city = params['city']
data_search = passData(sunElevation, cloudCoverage, thresholdNDVI, limitScene, city)
return jsonify(data_search.data_dict)
if __name__ == '__main__':
app.run()
Here is the definition of the class passData, in models.py :
class passData:
def __init__(self, sunElevation, cloudCoverage, thresholdNDVI, limitScene, city):
self.sunElevation = sunElevation
self.cloudCoverage = cloudCoverage
self.thresholdNDVI = thresholdNDVI
self.limitScene = limitScene
self.city = city
self.data_dict = [{'sunElevation':self.sunElevation,'cloudCoverage':self.cloudCoverage, 'thresholdNDVI':self.thresholdNDVI, 'limit':self.limitScene, 'city':self.city}]
I need to use those different parameters (sunElevation...) in an other script, in a other folder, to execute a search of imagery and then run the script associated. My problem is that I don't know how to pass those data, because they seem to only exist in the fonction defined in the get_javascript_data().
If someone has an idea that could help me !
You just have to import the other script, call the function and pass the parameters:
app = Flask(__name__)
app.config.from_object('config')
db.init_app(app)
from path.to.your.file import your_function
#app.route('/getFormData', methods=['POST'])
def get_javascript_data():
params = request.form.to_dict()
sunElevation = params['sunElevation']
cloudCoverage = params['cloudCoverage']
thresholdNDVI = params['thresholdNDVI']
limitScene = params['limitScene']
city = params['city']
data_search = passData(sunElevation, cloudCoverage, thresholdNDVI, limitScene, city)
# call the function and pass the parameters
your_function(sunElevation, cloudCoverage) #...
return jsonify(data_search.data_dict)
Try adding the following code in your file, then import the script
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
from eosLandviewer.main_naturalite import search

Categories

Resources