Skip to content

Instantly share code, notes, and snippets.

@abaranovskis-redsamurai
Created December 11, 2017 18:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save abaranovskis-redsamurai/811d090a8e8636744e854ba037519ada to your computer and use it in GitHub Desktop.
Save abaranovskis-redsamurai/811d090a8e8636744e854ba037519ada to your computer and use it in GitHub Desktop.
TensorFlow Linear Regression Model Access with Custom REST API using Flask
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):
# Create fake data for y = W.x + b where W = 2, b = 0
xs = np.array([[i]])
ys = np.array([[2*i]])
# 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