Created
January 15, 2018 17:02
-
-
Save abaranovskis-redsamurai/c7690d2732e531086c79716d0ba17720 to your computer and use it in GitHub Desktop.
Linear Regression Machine Learning with TensorFlow and Oracle JET UI Explained
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(): | |
learning_rate = 0.01 | |
training_epochs = 100 | |
# reading training parameters from REST request | |
if request.method == 'POST': | |
learning_rate = request.json['learningrate'] | |
training_epochs = request.json['trainingepochs'] | |
# training data | |
x_train = np.linspace(-1, 1, 101) | |
y_train = 2 * x_train + np.random.randn(*x_train.shape) * 0.33 | |
# placeholders, initialized from training data | |
X = tf.placeholder("float") | |
Y = tf.placeholder("float") | |
# model function, defined as y = W * x | |
def model(X, w): | |
return tf.multiply(X, w) | |
# weights variable for equation | |
w = tf.Variable(0.0, name="weights") | |
# cost function for linear regression, defined as the mean squared error | |
y_model = model(X, w) | |
cost = tf.reduce_mean(tf.square(Y-y_model)) | |
# This operation will be called on each iteration of the learning algorithm | |
# GradientDescentOptimizer - TensorFlow implementation | |
# Learn with given rate and try to minimize learning cost | |
train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) | |
# TensorFlow initialization | |
sess = tf.Session() | |
init = tf.global_variables_initializer() | |
sess.run(init) | |
# repeating training multiple times | |
for epoch in range(training_epochs): | |
# iterating through training data set and calling optimizer, for each training entry | |
for (x, y) in zip(x_train, y_train): | |
sess.run(train_op, feed_dict={X: x, Y: y}) | |
# calculated weights variable | |
w_val = sess.run(w) | |
# calculated cost variable | |
cost_val = sess.run(cost, feed_dict={X: x_train, Y: y_train}) | |
all_points = []; | |
eq_vals = []; | |
# populating array of x/y training data for REST response | |
for (x, y) in zip(x_train, y_train): | |
all_points.append({"x": x, "y": y}) | |
# populating weights and cost variables for REST response | |
eq_vals.append({"w": str(w_val), "cost": str(cost_val)}) | |
# constructing JSON response | |
response = jsonify(results=[eq_vals, all_points]) | |
sess.close() | |
return response | |
# running REST interface | |
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