| from flask import Flask, render_template, request, jsonify
|
| import numpy as np
|
|
|
| app = Flask(__name__)
|
|
|
|
|
|
|
|
|
| best = np.load("best_model.npy")
|
|
|
|
|
|
|
|
|
|
|
| train_mse = 0.005707
|
| test_mse = 0.008744
|
|
|
|
|
|
|
|
|
|
|
| input_dim = 1
|
| h1 = 32
|
| h2 = 16
|
| output_dim = 1
|
|
|
| D = input_dim*h1 + h1 + h1*h2 + h2 + h2*output_dim + output_dim
|
|
|
|
|
| def decode_theta(theta):
|
| idx = 0
|
| W1 = theta[idx:idx + input_dim*h1].reshape(input_dim, h1)
|
| idx += input_dim*h1
|
| b1 = theta[idx:idx + h1].reshape(1, h1)
|
| idx += h1
|
|
|
| W2 = theta[idx:idx + h1*h2].reshape(h1, h2)
|
| idx += h1*h2
|
| b2 = theta[idx:idx + h2].reshape(1, h2)
|
| idx += h2
|
|
|
| W3 = theta[idx:idx + h2*output_dim].reshape(h2, output_dim)
|
| idx += h2*output_dim
|
| b3 = theta[idx:idx + output_dim].reshape(1, output_dim)
|
|
|
| return W1, b1, W2, b2, W3, b3
|
|
|
|
|
| def fcnn_forward(X_batch, theta):
|
| W1, b1, W2, b2, W3, b3 = decode_theta(theta)
|
|
|
| z1 = X_batch @ W1 + b1
|
| a1 = np.maximum(z1, 0)
|
|
|
| z2 = a1 @ W2 + b2
|
| a2 = np.maximum(z2, 0)
|
|
|
| out = a2 @ W3 + b3
|
| return out
|
|
|
|
|
| def predict_next(theta, x):
|
| y = fcnn_forward(np.array([[x]]), theta)
|
| return float(y[0][0])
|
|
|
|
|
| def forecast_future(theta, x_start, steps=20):
|
| preds = []
|
| x = x_start
|
| for _ in range(steps):
|
| y = float(fcnn_forward(np.array([[x]]), theta)[0][0])
|
| preds.append(y)
|
| x = y
|
| return preds
|
|
|
|
|
|
|
|
|
|
|
|
|
| @app.route("/")
|
| def index():
|
| return render_template("index.html")
|
|
|
|
|
| @app.route("/predict", methods=["POST"])
|
| def predict():
|
| data = request.json.get("data", None)
|
| if data is None or len(data) == 0:
|
| return jsonify({"error": "No data provided"}), 400
|
|
|
| try:
|
| series = np.array(data, dtype=float)
|
| except:
|
| return jsonify({"error": "Invalid numeric data"}), 400
|
|
|
| last_val = float(series[-1])
|
| next_val = predict_next(best, last_val)
|
| future_vals = forecast_future(best, last_val, steps=20)
|
|
|
| return jsonify({
|
| "last": last_val,
|
| "next": next_val,
|
| "future": future_vals,
|
| "train_mse": train_mse,
|
| "test_mse": test_mse
|
| })
|
|
|
|
|
| if __name__ == "__main__":
|
| app.run(debug=True)
|
|
|