Write a program using tensorflow to calculate : $$y=mx+c$$
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))
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]: