I m currently deploying my LSTM model using flask python with HTML, I m facing the problem where I able to save my model but not able to predict the uploaded file in flask python, I really have no idea how it goes, so would like to have some precious guidance on this. Appreciate and Thank you
model.py
from numpy import loadtxt
from keras.models import Sequential
from keras.layers import Dense
import numpy
import matplotlib.pyplot as plt
import pandas
import math
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from keras.layers import Dropout
from keras.callbacks import EarlyStopping
# fix random seed for reproducibility
numpy.random.seed(7)
# load the dataset
dataframe = pandas.read_csv('Sales.csv', usecols=[1], engine='python', skipfooter=3)
dataset = dataframe.values
dataset = dataset.astype('float32')
dataset = numpy.reshape(dataset, (-1, 1))
# normalize the dataset
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
# split into train and test sets
train_size = int(len(dataset) * 0.80)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
print ("train_data_size: "+str(len(train)), " test_data_size: "+str(len(test)))
# convert an array of values into a dataset matrix
def create_dataset(dataset, look_back=1):
dataX, dataY = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back), 0]
dataX.append(a)
dataY.append(dataset[i + look_back, 0])
return numpy.array(dataX), numpy.array(dataY)
# reshape into X=t and Y=t+1
look_back = 3
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)
# reshape input to be [samples, time steps, features]
trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
# create and fit the LSTM network
model = Sequential()
model.add(LSTM(4, input_shape=(trainX.shape[1], trainX.shape[2])))
model.add(Dropout(0.2))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
history = model.fit(trainX, trainY, epochs= 300, batch_size=70, validation_data=(testX, testY),
callbacks=[EarlyStopping(monitor='val_loss', patience=10)], verbose=1, shuffle=False)
model.save("model.h5")
print("Saved model to disk")
app.py
from flask import Flask, make_response, request, render_template
import io
from io import StringIO
import csv
import pandas as pd
import numpy as np
import pickle
import os
from keras.models import load_model
app = Flask(__name__)
def transform(text_file_contents):
return text_file_contents.replace("=", ",")
@app.route('/')
def form():
return """
<html>
<body>
<h1>Let's TRY to Predict..</h1>
</br>
</br>
<p> Insert your CSV file and then download the Result
<form action="/transform" method="post" enctype="multipart/form-data">
<input type="file" name="data_file" class="btn btn-block"/>
</br>
</br>
<button type="submit" class="btn btn-primary btn-block btn-large">Predict</button>
</form>
</body>
</html>
"""
@app.route('/transform', methods=["POST"])
def transform_view():
f = request.files['data_file']
if not f:
return "No file"
stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None)
csv_input = csv.reader(stream)
#print("file contents: ", file_contents)
#print(type(file_contents))
print(csv_input)
for row in csv_input:
print(row)
stream.seek(0)
result = transform(stream.read())
df = pd.read_csv(StringIO(result))
# load the model from disk
model = load_model('model.h5')
df['prediction'] = model.predict(df)
response = make_response(df.to_csv())
response.headers["Content-Disposition"] = "attachment; filename=result.csv"
return response
if __name__ == "__main__":
app.run(debug=True, port = 9000, host = "localhost")
question from:
https://stackoverflow.com/questions/65933451/able-to-load-the-model-but-unable-to-predict-the-excel-file-in-flask-python