Skip to content

Instantly share code, notes, and snippets.

@abaranovskis-redsamurai
Created December 15, 2017 20:01
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save abaranovskis-redsamurai/ddc0891f19d4c2f094c1e64b0300729e to your computer and use it in GitHub Desktop.
TensorFlow Linear Regression Model Access with Custom REST API using Flask Raw
import numpy as np
import tensorflow as tf
from flask import Flask, jsonify, request
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
@app.route("/redsam/api/v0.1/points", methods=['GET', 'POST'])
def linear_regression_train():
# CUSTOMIZABLE: Collect/Prepare data
steps = 100
learn_rate = 0.0001
if request.method == 'POST':
steps = request.json['steps']
learn_rate = request.json['learnrate']
# Model linear regression y = Wx + b
x = tf.placeholder(tf.float32, [None, 1])
W = tf.Variable(tf.zeros([1,1]))
b = tf.Variable(tf.zeros([1]))
product = tf.matmul(x,W)
y = product + b
y_ = tf.placeholder(tf.float32, [None, 1])
# Cost function sum((y_-y)**2)
cost = tf.reduce_mean(tf.square(y_-y))
# Training using Gradient Descent to minimize cost
train_step = tf.train.GradientDescentOptimizer(learn_rate).minimize(cost)
sess = tf.Session()
init = tf.initialize_all_variables()
sess.run(init)
all_points = [];
eq_vals = [];
for i in range(steps):
if i % 10 != 0:
# Create fake data for x and y
xs = np.array([[i]])
ys = np.array([[2*i - 10]])
if i % 2 == 0:
ys = np.array([[2*i + 10]])
# Train
feed = { x: xs, y_: ys }
sess.run(train_step, feed_dict=feed)
all_points.append({"x": xs[0][0], "y": ys[0][0]});
# NOTE: W should be close to 2, and b should be close to 0
eq_vals.append({'w': str(sess.run(W)[0][0]), "b": str(sess.run(b)[0]),
"cost": '{0:f}'.format(sess.run(cost, feed_dict=feed))});
response = jsonify(results=[eq_vals, all_points])
return response
if __name__ == "__main__":
app.run(host='0.0.0.0')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment