Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
8ba3ef4
new
ipolychr Jul 13, 2019
128c00e
'api'
ipolychr Jul 13, 2019
c614daa
this is it
ipolychr Jul 15, 2019
0967896
intermediate version wt multiple columns
mihalispap Jul 15, 2019
4e788c5
intermediate commit
mihalispap Jul 17, 2019
424fdd3
int. commit for multiple cols at reshape
mihalispap Jul 17, 2019
a9c8141
applied norm func
mihalispap Jul 17, 2019
9286d50
take into account only year
mihalispap Jul 17, 2019
0aa98ab
sync commit
mihalispap Jul 17, 2019
33967e9
intermediate commit
mihalispap Jul 17, 2019
95a5fe4
dummy commit
mihalispap Jul 17, 2019
1b99fbb
intermediate commit
mihalispap Jul 17, 2019
0a406a9
intermediate commit
mihalispap Jul 17, 2019
08b0e89
init prophet test
mihalispap Jul 17, 2019
1f48622
added ref link for moving averages
mihalispap Jul 17, 2019
3dba296
@@@ o dias
ipolychr Jul 17, 2019
0d16509
hhhhh
ipolychr Jul 17, 2019
0969e7a
@@@ o dias
ipolychr Jul 17, 2019
ac6edd6
@@@ o dias
ipolychr Jul 18, 2019
514d179
prophet v0.9
mihalispap Jul 18, 2019
b8228ea
'api'
ipolychr Jul 13, 2019
b171c6a
rebased master into api_creation
mihalispap Jul 18, 2019
e7b48f2
new
ipolychr Jul 13, 2019
284a985
'api'
ipolychr Jul 13, 2019
0fa23fc
this is it
ipolychr Jul 15, 2019
917a936
hh
ipolychr Jul 18, 2019
9e3f790
Merge branch 'api_creation_multiple_cols' of https://github.com/agrok…
ipolychr Jul 18, 2019
e04f8e1
train & predict lstm v1.0
mihalispap Jul 19, 2019
22c2e45
sync commit
mihalispap Jul 19, 2019
bc16df2
working
ipolychr Jul 19, 2019
caa1f33
sample bulk training ^ plots
mihalispap Jul 22, 2019
fa823ad
h
ipolychr Jul 22, 2019
2f19414
Merge branch 'api_creation' of https://github.com/agroknow/PricePredi…
ipolychr Jul 22, 2019
b1647fd
new algorithm
ipolychr Jul 23, 2019
d70d5b0
Merge branch 'api_creation_multiple_cols' of https://github.com/agrok…
mihalispap Jul 23, 2019
ba0729b
new
ipolychr Jul 24, 2019
7955c3d
prophet v1.0
mihalispap Jul 24, 2019
090d50e
Merge branch 'api_creation_multiple_cols' of https://github.com/agrok…
mihalispap Jul 24, 2019
e78c58c
prophet v2.0
mihalispap Jul 24, 2019
e4278cc
k
ipolychr Jul 24, 2019
13e22db
Merge branch 'api_creation_multiple_cols' of https://github.com/agrok…
ipolychr Jul 24, 2019
ae6c8a2
k
ipolychr Jul 25, 2019
1177567
intermediate commit
mihalispap Jul 25, 2019
6bbd526
Merge branch 'api_creation_multiple_cols' of https://github.com/agrok…
mihalispap Jul 25, 2019
3ce35dd
api
ipolychr Jul 25, 2019
5ddfb72
new add
ipolychr Jul 30, 2019
e818bc9
Merge branch 'api_creation_multiple_cols' of https://github.com/agrok…
ipolychr Jul 30, 2019
bd32f05
lstm4all
ipolychr Aug 1, 2019
6f39934
new
ipolychr Aug 10, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
Binary file added api/Train_results.db
Binary file not shown.
Binary file added api/__pycache__/app.cpython-37.pyc
Binary file not shown.
314 changes: 314 additions & 0 deletions api/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,314 @@
import json
import pickle
import pandas as pd
import numpy as np
from flask import Flask
from flask import request, jsonify
from tabulate import tabulate
from operator import itemgetter, attrgetter
from api.utils.LSTMModel import LSTMModel

app = Flask(__name__)
app.config["DEBUG"] = True


@app.route('/')
def hello_world():
return 'Hello World!'


@app.route('/train', methods=['GET'])
def api_training():
parameters = request.args

product = parameters.get('product')
country = parameters.get('country')
data_Source = parameters.get('data_Source')

import pandas as pd
import numpy as np

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
import seaborn as sns
from keras.callbacks import TensorBoard, EarlyStopping, ModelCheckpoint
scaler = MinMaxScaler(feature_range=(0, 1))
import requests
import json
response = requests.get("http://148.251.22.254:8080/price-api-1.0/price/findAll")
data = response.text
parsed = json.loads(data)
# print(json.dumps(parsed, indent=4))

# dataframe
df = pd.DataFrame(parsed)

sns.set_style('darkgrid')
# df = pd.read_csv("food_dataset.csv")
dfevoo = df
print(dfevoo)
if product:
# dfevoo = df[df['product'] == product]


dfevoo = df[df['product'].str.contains("garlic - ail, white, cat. i, cal. 50-80")]
if country:
print(dfevoo)
# dfevoo = dfevoo[dfevoo['country'] == country]
if data_Source:
# dfevoo = dfevoo[dfevoo['dataSource'] == data_Source]
dfevoo = dfevoo[dfevoo['dataSource'].str.contains(data_Source)]

print(dfevoo)

if not (product or country or data_Source):
return page_not_found(404)

dfevoo['priceStringDate'] = pd.to_datetime(dfevoo['priceStringDate'])
dfevoo = dfevoo.drop(columns=['price_id', 'product', 'priceDate', 'url', 'country', 'dataSource']).sort_values(
by='priceStringDate')
dfevoo = pd.DataFrame(dfevoo)
dfevoo = dfevoo.groupby('priceStringDate').mean().reset_index()
Data = dfevoo
print(Data)
# Long Short Term Memory (LSTM)

# setting index
Data.index = Data.priceStringDate
Data.drop('priceStringDate', axis=1, inplace=True)

# lb = 80
rms = [[]]

for lb in range(55, 65, 1):
# creating train and test sets
dataset = Data.values
scaler = MinMaxScaler(feature_range=(0, 1))
scaler.fit(dataset)

test = dataset[len(dataset) - lb:, :]
dataset = dataset[:len(dataset) - lb, :]
train = dataset[:len(dataset) - lb, :]
# valid = dataset[int(0.2 * (len(dataset))):, :]
scaled_data = scaler.transform(train)
# Convert Training Data to Right Shape
x_train = []
y_train = []
for i in range(lb, len(train)):
x_train.append(scaled_data[i - lb:i, 0])
y_train.append(scaled_data[i, 0])

x_train = np.array(x_train)
y_train = np.array(y_train)

x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))

model = LSTMModel(x_train=x_train)

keras_callbacks = [
EarlyStopping(monitor='loss', patience=20, verbose=0)
]
config = {}
config['epochs'] = 1000
config['batch_size'] = 32
config['verbose'] = 1
config['callbacks'] = keras_callbacks

model.fit(features=x_train, labels=y_train, config=config)

predictions = []
for preds in range(0, lb + 1):

valid = dataset[len(dataset) - lb:]
inputs = valid

# Scale our test data
inputs = inputs.reshape(-1, 1)
inputs = scaler.transform(inputs)

# final test input
X_test = []
for i in range(lb, inputs.shape[0] + 1):
X_test.append(inputs[i - lb:i, 0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))

closing_price = scaler.inverse_transform(model.predict(data=X_test))

predictions.append(closing_price.flatten()[0])

dataset = np.append(dataset, np.array([closing_price.flatten()[0]]))

plt.plot(predictions, color='green', label='Predicted')
plt.plot(test, color='blue', label='Actual')
plt.title('Price Prediction ')
plt.xlabel('date')
plt.ylabel('price')
plt.legend()
plt.savefig('plots/pred_1_%s.png' % str(lb), bbox_inches='tight')
plt.show()

complete_pred = []
for val in train:
complete_pred.append(val)
for pred in predictions:
complete_pred.append(pred)

actual = []
for val in train:
actual.append(val)
for val in test:
actual.append(val)

plt.plot(complete_pred, color='green', label='Predicted')
plt.plot(actual, color='blue', label='Actual')
plt.title('Price Prediction ')
plt.xlabel('date')
plt.ylabel('price')
plt.legend()
plt.savefig('plots/pred_2_%s.png' % str(lb), bbox_inches='tight')
plt.show()
rmse = np.sqrt(np.mean(np.power((test - closing_price), 2)))
rms.append([rmse, lb])

print(rms)

with open('filename.txt', 'w') as outputfile:
outputfile.write(tabulate(rms))
dictionary = {'predictions': predictions}
return json.dumps(str(dictionary))


# import pickle
#
# pickle.dump(fitted_model, open("model_fit.pkl", "wb"), pickle.HIGHEST_PROTOCOL)
#
# import sqlite3
#
# conn = sqlite3.connect('Train_results.db')
#
# c = conn.cursor()
# c.execute('''
# INSERT INTO TrainingResults(Product_Name,Country_Name,Data_Source,Model_fit)
# VALUES (?,?,?,?) ''', (product, country, data_Source, open('model_fit.pkl', 'rb').read()))
#
# c.execute('''
# SELECT *
# FROM TrainingResults
# ''')
# print(c.fetchall())
# conn.commit()
#
# return "geiaa"
# return jsonify(fitted_model.tolist())


@app.route('/prediction', methods=['GET'])
def api_prediction():
# parameters = request.args
#
# product = parameters.get('product')
# country = parameters.get('country')
# data_Source = parameters.get('data_Source')
# # date = parameters.get('date')
# if not (product or country or data_Source):
# return page_not_found(404)

#
# from keras.models import Sequential
# from keras.layers import Dense
# from keras.layers import Dropout
# from keras.layers import LSTM
# from sklearn.preprocessing import MinMaxScaler
# import matplotlib.pyplot as plt
# import seaborn as sns
# from keras.callbacks import TensorBoard, EarlyStopping, ModelCheckpoint
# scaler = MinMaxScaler(feature_range=(0, 1))
#
# sns.set_style('darkgrid')
# import sqlite3
# conn = sqlite3.connect('Train_results.db')
# c = conn.cursor()
# results = c.execute(
# 'SELECT Model_fit FROM TrainingResults WHERE Product_Name=? and Country_Name=? and Data_Source=?',
# (product, country, data_Source)).fetchall()
# print('to brhka')
# if not results:
# results = api_training()
# print('de to brhka')

model = pickle.load(open('model_fit.pkl', 'rb'))
dfevoo = pd.read_csv("food_dataset.csv")
dfevoo['priceStringDate'] = pd.to_datetime(dfevoo['priceStringDate'])
fevoo = dfevoo.drop(columns=['price_id', 'product', 'priceDate', 'url', 'country', 'dataSource']).sort_values(
by='priceStringDate')
dfevoo = pd.DataFrame(dfevoo)
dfevoo = dfevoo.groupby('priceStringDate').mean().reset_index()
Data = dfevoo
# Prepare our test inputs
dataset = Data.values
lb = 1
valid = dataset[int(0.2 * (len(dataset))):, :]
inputs = Data[len(Data) - len(valid) - lb:].values

# Scale our test data
inputs = inputs.reshape(-1, 1)
inputs = scaler.transform(inputs)

# final test input
X_test = []
for i in range(lb, inputs.shape[0]):
X_test.append(inputs[i - lb:i, 0])

closing_price = model.predict(X_test)
return jsonify(closing_price.flatten())
#
# dfevoo = pd.read_csv("food_dataset.csv")
# dfevoo['priceStringDate'] = pd.to_datetime(dfevoo['priceStringDate'])
# fevoo = dfevoo.drop(columns=['price_id', 'product', 'priceDate', 'url', 'country', 'dataSource']).sort_values(
# by='priceStringDate')
# dfevoo = pd.DataFrame(dfevoo)
# dfevoo = dfevoo.groupby('priceStringDate').mean().reset_index()
# Data = dfevoo
# # Prepare our test inputs
# dataset = Data.values
# lb = 1
# valid = dataset[int(0.2 * (len(dataset))):, :]
# inputs = Data[len(Data) - len(valid) - lb:].values
#
# # Scale our test data
# inputs = inputs.reshape(-1, 1)
# inputs = scaler.transform(inputs)
#
# # final test input
# X_test = []
# for i in range(lb, inputs.shape[0]):
# X_test.append(inputs[i - lb:i, 0])
#
# # Convert our data into the three-dimensional format which can be used as input to the LSTM.
# X_test = np.array(X_test)
# X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
#
# # Making Predictions
# closing_price = model.predict(X_test)
# # reverse the scaled prediction back to their actual values.
# # Use the ìnverse_transform method of the scaler object we created during training
# closing_price = scaler.inverse_transform(closing_price)
#
#
# # return jsonify(closing_price.tolist())
# return jsonify(closing_price)
return "j"


@app.errorhandler(404)
def page_not_found(e):
return "<h1>404</h1><p>The resource could not be found.</p>", 404


if __name__ == '__main__':
app.run()
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added api/blé dur - durum wheat/pred_1_55.png
Binary file added api/blé dur - durum wheat/pred_1_56.png
Binary file added api/blé dur - durum wheat/pred_1_57.png
Binary file added api/blé dur - durum wheat/pred_1_58.png
Binary file added api/blé dur - durum wheat/pred_1_59.png
Binary file added api/blé dur - durum wheat/pred_1_60.png
Binary file added api/blé dur - durum wheat/pred_1_61.png
Binary file added api/blé dur - durum wheat/pred_1_62.png
Binary file added api/blé dur - durum wheat/pred_1_63.png
Binary file added api/blé dur - durum wheat/pred_1_64.png
Binary file added api/blé dur - durum wheat/pred_1_65.png
Binary file added api/blé dur - durum wheat/pred_2_55.png
Binary file added api/blé dur - durum wheat/pred_2_56.png
Binary file added api/blé dur - durum wheat/pred_2_57.png
Binary file added api/blé dur - durum wheat/pred_2_58.png
Binary file added api/blé dur - durum wheat/pred_2_59.png
Binary file added api/blé dur - durum wheat/pred_2_60.png
Binary file added api/blé dur - durum wheat/pred_2_61.png
Binary file added api/blé dur - durum wheat/pred_2_62.png
Binary file added api/blé dur - durum wheat/pred_2_63.png
Binary file added api/blé dur - durum wheat/pred_2_64.png
Binary file added api/blé dur - durum wheat/pred_2_65.png
Binary file added api/broiler - poulet, 65%/pred_1_55.png
Binary file added api/broiler - poulet, 65%/pred_1_56.png
Binary file added api/broiler - poulet, 65%/pred_1_57.png
Binary file added api/broiler - poulet, 65%/pred_1_58.png
Binary file added api/broiler - poulet, 65%/pred_1_59.png
Binary file added api/broiler - poulet, 65%/pred_1_60.png
Binary file added api/broiler - poulet, 65%/pred_1_61.png
Binary file added api/broiler - poulet, 65%/pred_1_62.png
Binary file added api/broiler - poulet, 65%/pred_1_63.png
Binary file added api/broiler - poulet, 65%/pred_1_64.png
Binary file added api/broiler - poulet, 65%/pred_1_65.png
Binary file added api/broiler - poulet, 65%/pred_2_55.png
Binary file added api/broiler - poulet, 65%/pred_2_56.png
Binary file added api/broiler - poulet, 65%/pred_2_57.png
Binary file added api/broiler - poulet, 65%/pred_2_58.png
Binary file added api/broiler - poulet, 65%/pred_2_59.png
Binary file added api/broiler - poulet, 65%/pred_2_60.png
Binary file added api/broiler - poulet, 65%/pred_2_61.png
Binary file added api/broiler - poulet, 65%/pred_2_62.png
Binary file added api/broiler - poulet, 65%/pred_2_63.png
Binary file added api/broiler - poulet, 65%/pred_2_64.png
Binary file added api/broiler - poulet, 65%/pred_2_65.png
Binary file added api/butter - beurre/pred_1_55.png
Binary file added api/butter - beurre/pred_1_56.png
Binary file added api/butter - beurre/pred_1_57.png
Binary file added api/butter - beurre/pred_1_58.png
Binary file added api/butter - beurre/pred_1_59.png
Binary file added api/butter - beurre/pred_1_60.png
Binary file added api/butter - beurre/pred_1_61.png
Binary file added api/butter - beurre/pred_1_62.png
Binary file added api/butter - beurre/pred_1_63.png
Binary file added api/butter - beurre/pred_1_64.png
Binary file added api/butter - beurre/pred_1_65.png
Binary file added api/butter - beurre/pred_2_55.png
Binary file added api/butter - beurre/pred_2_56.png
Binary file added api/butter - beurre/pred_2_57.png
Binary file added api/butter - beurre/pred_2_58.png
Binary file added api/butter - beurre/pred_2_59.png
Binary file added api/butter - beurre/pred_2_60.png
Binary file added api/butter - beurre/pred_2_61.png
Binary file added api/butter - beurre/pred_2_62.png
Binary file added api/butter - beurre/pred_2_63.png
Binary file added api/butter - beurre/pred_2_64.png
Binary file added api/butter - beurre/pred_2_65.png
Binary file added api/butter/pred_1_55.png
Binary file added api/butter/pred_1_56.png
Binary file added api/butter/pred_1_57.png
Binary file added api/butter/pred_1_58.png
Binary file added api/butter/pred_1_59.png
Binary file added api/butter/pred_1_60.png
Binary file added api/butter/pred_1_61.png
Binary file added api/butter/pred_1_62.png
Binary file added api/butter/pred_1_63.png
Binary file added api/butter/pred_1_64.png
Binary file added api/butter/pred_1_65.png
Binary file added api/butter/pred_2_55.png
Binary file added api/butter/pred_2_56.png
Binary file added api/butter/pred_2_57.png
Binary file added api/butter/pred_2_58.png
Binary file added api/butter/pred_2_59.png
Binary file added api/butter/pred_2_60.png
Binary file added api/butter/pred_2_61.png
Binary file added api/butter/pred_2_62.png
Binary file added api/butter/pred_2_63.png
Binary file added api/butter/pred_2_64.png
Binary file added api/butter/pred_2_65.png
Binary file added api/edam - edam/pred_1_55.png
Binary file added api/edam - edam/pred_1_56.png
Binary file added api/edam - edam/pred_1_57.png
Binary file added api/edam - edam/pred_1_58.png
Binary file added api/edam - edam/pred_1_59.png
Binary file added api/edam - edam/pred_2_55.png
Binary file added api/edam - edam/pred_2_56.png
Binary file added api/edam - edam/pred_2_57.png
Binary file added api/edam - edam/pred_2_58.png
Binary file added api/edam - edam/pred_2_59.png
Binary file added api/edam/pred_1_55.png
Binary file added api/edam/pred_1_56.png
Binary file added api/edam/pred_1_57.png
Binary file added api/edam/pred_1_58.png
Binary file added api/edam/pred_1_59.png
Binary file added api/edam/pred_1_60.png
Binary file added api/edam/pred_1_61.png
Binary file added api/edam/pred_1_62.png
Binary file added api/edam/pred_1_63.png
Binary file added api/edam/pred_1_64.png
Binary file added api/edam/pred_1_65.png
Loading