forked from jbagnato/machine-learning
-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Agrego ejemplo de crear api Flask para machine learning
- Loading branch information
jbagnatoMacPro
committed
Jul 23, 2019
1 parent
2327c34
commit 5ee6006
Showing
7 changed files
with
839 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
import pandas as pd | ||
import numpy as np | ||
from sklearn.preprocessing import MinMaxScaler | ||
|
||
from utiles import * | ||
|
||
df = pd.read_csv('time_series.csv', parse_dates=[0], header=None,index_col=0, names=['fecha','unidades']) | ||
df['weekday']=[x.weekday() for x in df.index] | ||
df['month']=[x.month for x in df.index] | ||
print(df.head()) | ||
|
||
EPOCHS=40 | ||
PASOS=7 | ||
|
||
scaler = MinMaxScaler(feature_range=(-1, 1)) | ||
|
||
reframed = transformar(df, scaler) | ||
|
||
reordenado=reframed[ ['weekday','month','var1(t-7)','var1(t-6)','var1(t-5)','var1(t-4)','var1(t-3)','var1(t-2)','var1(t-1)','var1(t)'] ] | ||
reordenado.dropna(inplace=True) | ||
|
||
training_data = reordenado.drop('var1(t)', axis=1) | ||
target_data=reordenado['var1(t)'] | ||
cant = len(df.index) | ||
valid_data = training_data[cant-30:cant] | ||
valid_target=target_data[cant-30:cant] | ||
|
||
training_data = training_data[0:cant] | ||
target_data=target_data[0:cant] | ||
print(training_data.shape, target_data.shape, valid_data.shape, valid_target.shape) | ||
print(training_data.head()) | ||
|
||
model = crear_modeloEmbeddings() | ||
|
||
continuas = training_data[['var1(t-7)','var1(t-6)','var1(t-5)','var1(t-4)','var1(t-3)','var1(t-2)','var1(t-1)']] | ||
valid_continuas = valid_data[['var1(t-7)','var1(t-6)','var1(t-5)','var1(t-4)','var1(t-3)','var1(t-2)','var1(t-1)']] | ||
|
||
history = model.fit([training_data['weekday'],training_data['month'],continuas], target_data, epochs=EPOCHS, | ||
validation_data=([valid_data['weekday'],valid_data['month'],valid_continuas],valid_target)) | ||
|
||
results = model.predict([valid_data['weekday'],valid_data['month'],valid_continuas]) | ||
|
||
print( 'Resultados escalados',results ) | ||
inverted = scaler.inverse_transform(results) | ||
print( 'Resultados',inverted ) | ||
|
||
save_object('scaler_time_series.pkl', scaler) | ||
model.save('red_time_series.h5') | ||
model.save_weights("pesos.h5") | ||
|
||
#loaded_model = load_model('red_time_series.h5') | ||
loaded_model = crear_modeloEmbeddings() | ||
loaded_model.load_weights("pesos.h5") | ||
|
||
results = loaded_model.predict([valid_data['weekday'],valid_data['month'],valid_continuas]) | ||
print( 'Resultados escalados',results ) | ||
loaded_scaler = load_object('scaler_time_series.pkl') | ||
inverted = loaded_scaler.inverse_transform(results) | ||
print( 'Resultados',inverted ) |
Binary file not shown.
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
"""Filename: server.py | ||
""" | ||
import pandas as pd | ||
from sklearn.externals import joblib | ||
from flask import Flask, jsonify, request | ||
|
||
from utiles import * | ||
|
||
app = Flask(__name__) | ||
|
||
@app.route('/predict', methods=['POST']) | ||
def predict(): | ||
"""API request | ||
""" | ||
try: | ||
req_json = request.get_json() | ||
input = pd.read_json(req_json, orient='records') | ||
except Exception as e: | ||
raise e | ||
|
||
if input.empty: | ||
return(bad_request()) | ||
else: | ||
#Load the saved model | ||
print("Cargar el modelo...") | ||
loaded_model = crear_modeloEmbeddings() | ||
loaded_model.load_weights("pesos.h5") | ||
|
||
print("Hacer Pronosticos") | ||
continuas = input[['var1(t-7)','var1(t-6)','var1(t-5)','var1(t-4)','var1(t-3)','var1(t-2)','var1(t-1)']] | ||
predictions = loaded_model.predict([input['weekday'], input['month'], continuas]) | ||
|
||
print("Transformando datos") | ||
loaded_scaler = load_object('scaler_time_series.pkl') | ||
inverted = loaded_scaler.inverse_transform(predictions) | ||
inverted = inverted.astype('int32') | ||
|
||
final_predictions = pd.DataFrame(inverted) | ||
final_predictions.columns = ['ventas'] | ||
|
||
print("Enviar respuesta") | ||
responses = jsonify(predictions=final_predictions.to_json(orient="records")) | ||
responses.status_code = 200 | ||
print("Fin de Peticion") | ||
|
||
return (responses) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import json | ||
import requests | ||
import pandas as pd | ||
import pickle | ||
from utiles import * | ||
|
||
"""Setting the headers to send and accept json responses | ||
""" | ||
header = {'Content-Type': 'application/json', \ | ||
'Accept': 'application/json'} | ||
|
||
# creamos un dataset de pruebas | ||
df = pd.DataFrame({"unidades": [289,288,260,240,290,255,270,300], | ||
"weekday": [5,0,1,2,3,4,5,0], | ||
"month": [4,4,4,4,4,4,4,4]}) | ||
|
||
loaded_scaler = load_object('scaler_time_series.pkl') | ||
|
||
reframed = transformar(df, loaded_scaler) | ||
|
||
reordenado=reframed[ ['weekday','month','var1(t-7)','var1(t-6)','var1(t-5)','var1(t-4)','var1(t-3)','var1(t-2)','var1(t-1)'] ] | ||
reordenado.dropna(inplace=True) | ||
#print(reordenado) | ||
|
||
"""Converting Pandas Dataframe to json | ||
""" | ||
data = reordenado.to_json(orient='records') | ||
|
||
print('JSON para enviar en POST', data) | ||
|
||
"""POST <url>/predict | ||
""" | ||
resp = requests.post("http://localhost:8000/predict", \ | ||
data = json.dumps(data),\ | ||
headers= header) | ||
|
||
print('status',resp.status_code) | ||
|
||
|
||
print('Respuesta de Servidor') | ||
print(resp.json()) | ||
|
Oops, something went wrong.