-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_model.py
More file actions
63 lines (50 loc) · 2.36 KB
/
Copy pathapp_model.py
File metadata and controls
63 lines (50 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from flask import Flask, jsonify, request
import os
import pickle
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Lasso
from sklearn.metrics import mean_squared_error, mean_absolute_percentage_error
import numpy as np
# os.chdir(os.path.dirname(__file__))
app = Flask(__name__)
# Enruta la landing page (endpoint /)
@app.route("/", methods=["GET"])
def hello(): # Ligado al endopoint "/" o sea el home, con el método GET
return "<h1>Bienvenido a mi API del modelo advertising</h1>"
# Enruta la funcion al endpoint /api/v1/predict
@app.route("/api/v1/predict", methods=["GET"])
def predict(): # Ligado al endpoint '/api/v1/predict', con el método GET
with open('ad_model.pkl', 'rb') as f:
model = pickle.load(f)
tv = request.args.get('tv', None)
radio = request.args.get('radio', None)
newspaper = request.args.get('newspaper', None)
print(tv,radio,newspaper)
print(type(tv))
if tv is None or radio is None or newspaper is None:
return "Args empty, not enough data to predict"
else:
prediction = model.predict([[float(tv),float(radio),float(newspaper)]])
return jsonify({'predictions': prediction[0]})
# Enruta la funcion al endpoint /api/v1/retrain
@app.route("/api/v1/predict", methods=["GET"])
def retrain(): # Ligado al endpoint '/api/v1/retrain/', metodo GET
if os.path.exists("data/Advertising_new.csv"):
data = pd.read_csv('data/Advertising_new.csv')
X_train, X_test, y_train, y_test = train_test_split(data.drop(columns=['sales']),
data['sales'],
test_size = 0.20,
random_state=42)
model = Lasso(alpha=6000)
model.fit(X_train, y_train)
rmse = np.sqrt(mean_squared_error(y_test, model.predict(X_test)))
mape = mean_absolute_percentage_error(y_test, model.predict(X_test))
model.fit(data.drop(columns=['sales']), data['sales'])
with open('ad_model.pkl', 'wb') as f:
pickle.dump(model, f)
return f"Model retrained. New evaluation metric RMSE: {str(rmse)}, MAPE: {str(mape)}"
else:
return f"<h2>New data for retrain NOT FOUND. Nothing done!</h2>"
if __name__ == '__main__':
app.run(debug=True)