Write a program using tensorflow to calculate : $$y=mx+c$$

Part 1

  1. Read 2 arrays x,y containing floating point values
  2. Calculate mean of x & y
  3. Calculate variance for x $$variance(x)=sum((x-mean(x))^2)$$
  4. Calculate covariance of x & y $$covariance = sum((x(i) - mean(x)) * (y(i) - mean(y)))$$
  5. Calculate value of m $$m = covariance(x,y)/variance(x)$$
  6. Calculate value of c $$c = mean(y) -m* mean(x)$$

Part 2

  1. Plot graph for actual values against predicted value
  2. Calculate root mean square error.

In [1]:
## Calculate mean of  X and Y
import tensorflow as tf
x=tf.constant([4,3,5],dtype=tf.float32)
y=tf.constant([8,9,5],dtype=tf.float32)
x_mean=0
y_mean=0
for i in range(0,3):
    with tf.name_scope("mean_x"):
        x_mean=tf.add(x[i],x_mean)
    with tf.name_scope("mean_y"):
        y_mean=tf.add(y[i],y_mean)
    x_mean=tf.div(x_mean,3)
    y_mean=tf.div(y_mean,3)
            
    
    ##variance(x)=sum((x−mean(x))2


var_x=0
var_y=0
for i in range(0,3):
     var_x=tf.add(tf.pow(tf.subtract(x[i],x_mean),2),var_x)
     var_y=tf.add(tf.pow(tf.subtract(y[i],y_mean),2),var_y)
with tf.name_scope("variance_X"):
         var_x=tf.div(var_x,2)
with tf.name_scope("variance_Y"):
         var_y=tf.div(var_y,2)
        
#covariance=sum((x(i)−mean(x))∗(y(i)−mean(y)))

with tf.name_scope("Covariance"):
    covar=0
    for i in range(0,3):
        covar=tf.add(tf.multiply(tf.subtract(x[i],x_mean),tf.subtract(y[i],y_mean)),covar)
    
#m=covariance(x,y)/variance(x)

with tf.name_scope("value_of_m"):
    m=tf.div(covar,var_x)
   
    #c=mean(y)−m∗mean(x)
with tf.name_scope("value_of_c"):
    c=tf.subtract(y_mean,tf.multiply(m,x_mean))
with tf.Session() as sess:
    print(sess.run(x_mean))
    print(sess.run(y_mean))
    print(sess.run(var_x))
    print(sess.run(var_y))
    print(sess.run(covar))
    print(sess.run(m))
    print(sess.run(c))


2.14815
2.96296
6.14403
32.9835
20.2798
3.30074
-4.12751

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]: