Skip to content

Instantly share code, notes, and snippets.

@shubham-sharma-ai
Created November 20, 2018 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shubham-sharma-ai/bdfe966820acc758b38c29284e2edb0c to your computer and use it in GitHub Desktop.
Save shubham-sharma-ai/bdfe966820acc758b38c29284e2edb0c to your computer and use it in GitHub Desktop.
Determining equation using Tensorflow
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
size = 10000
def generate_data(size):
x = np.array(np.random.rand(size,))
y = 8 * (x**2) + 8*x + 5
return x,y
train_x,train_y = generate_data(size)
x = tf.placeholder(tf.float32,shape=(None,))
y = tf.placeholder(tf.float32,shape=(None,))
A = tf.Variable(np.random.normal(),dtype=tf.float32)
B = tf.Variable(np.random.normal(),dtype=tf.float32)
C = tf.Variable(np.random.normal(),dtype=tf.float32)
p1 = tf.Variable(np.random.normal(),dtype=tf.float32)
y_pred = A * x ** p1 + B * x + C
loss = tf.reduce_mean(tf.square((y_pred - y)))
optimizer = tf.train.AdamOptimizer(0.01).minimize(loss)
iterations = 0
loss_hist = []
with tf.Session() as session:
session.run(tf.global_variables_initializer())
loss_val = 1000
while(loss_val > 0.000000001):
loss_val,_ = session.run([loss,optimizer],feed_dict={x:train_x,y:train_y})
iterations = iterations + 1
if iterations%5000 == 0:
print(iterations," ",loss_val)
loss_hist.append(loss_val)
print("After {} Iterations : \n".format(iterations))
print("Equation : \t y = {:2f}x^{} + {}x + {}".format(A.eval(),p1.eval(),B.eval(),C.eval()))
plt.plot(loss_hist)
plt.xlabel("Iterations")
plt.ylabel("loss value")
plt.title("minimum loss : {}".format(str(min(loss_hist))))
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment