This code fits a simple Linear Model y = W*x+b where (x,y) are the input data and W - weights and b-biases respectively. This code uses Gradient Descent Optimizer of Tensor flow to perform gradient descent and converge on the Weights and biases
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
# Training Data
train_X = np.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,
7.042,10.791,5.313,7.997,5.654,9.27,3.1])
train_Y = np.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,
2.827,3.465,1.65,2.904,2.42,2.94,1.3])
n_samples = train_X.shape[0]
# Input to Tensorflow
X= tf.placeholder("float")
Y= tf.placeholder("float")
W = tf.Variable(np.random.randn(),"Weight")
b = tf.Variable(np.random.randn(), "Bias")
#Predicted Value
Y_Pred = tf.multiply(X,W)+b
# L2 Loss
#cost = tf.reduce_mean(tf.pow(Y_Pred - Y,2))
cost = tf.reduce_sum(tf.pow(Y_Pred-Y, 2))/(n_samples)
learning_rate = 0.014
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
init = tf.global_variables_initializer()
#Variables for number of epochs and when to display error
epochs = 1000
displayStep = 50
with tf.Session() as sess:
sess.run(init)
for epoch in range(epochs):
for (x,y) in zip(train_X,train_Y):
sess.run(optimizer,feed_dict={X:x,Y:y})
if(epoch%displayStep == 0):
c=sess.run(cost,feed_dict={X:train_X,Y:train_Y})
print("Epcoh = ",epoch,"Cost = ", c,"W =", sess.run(W), "b =" ,sess.run(b))
#Plot the Data and the fitted line.
#Note this is being done inside the session inorder to access 'W' and 'b'
plt.plot(train_X,train_Y,'ro',label="Original Data")
Pred_Y = sess.run(W)*train_X+sess.run(b)
plt.plot(train_X,Pred_Y,label="Fitted Line")
plt.legend()
plt.show()
Credits: Took Inspiration from https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/2_BasicModels/linear_regression.ipynb