Created
November 20, 2018 09:31
-
-
Save shubham-sharma-ai/bdfe966820acc758b38c29284e2edb0c to your computer and use it in GitHub Desktop.
Determining equation using Tensorflow
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 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