You are on page 1of 5

https://codability.

in/a-guide-to-tensorflow-linear-regression-part-5/

Reference:

# D G Kleinbaum and L L Kupper,

# Applied Regression Analysis and Other Multivariable Methods,

# Duxbury Press, 1978, page 149.

# Helmut Spaeth,

# Mathematical Algorithms for Linear Regression,

# Academic Press, 1991,

# ISBN 0-12-656460-4.

# Discussion:

# Age and weight are to be related to blood fat content.

# There are 25 rows of data. The data columns include:

# I, the index;

# A0, 1;

# A1, the weight;

# A2, the age;

# B, the blood fat content.

#
# We seek a model of the form:

# B = A0 * X0 + A1 * X1 + A2 * X2.

5 columns

25 rows

Index

One

Weight (kilograms)

Age (Years)

Blood fat content

1 1 84 46 354

2 1 73 20 190

3 1 65 52 405

4 1 70 30 263

5 1 76 57 451

6 1 69 25 302

7 1 63 28 288

8 1 72 36 385

9 1 79 57 402

10 1 75 44 365

11 1 27 24 209

12 1 89 31 290

13 1 65 52 346

14 1 57 23 254
15 1 59 60 395

16 1 69 48 434

17 1 60 34 220

18 1 79 51 374

19 1 75 50 308

20 1 82 34 220

21 1 59 46 311

22 1 67 23 181

23 1 85 37 274

24 1 55 40 303

25 1 63 30 244

Solution in Tensorflow -

import tensorflow as t

W = t.Variable(t.zeros([2, 1]), name="weights")

b = t.Variable(0., name="bias")

def inputs():

weight_age = [[84, 46], [73, 20], [65, 52], [70, 30], [76, 57], [69, 25], [63, 28], [72, 36], [79, 57],
[75, 44], [27, 24], [89, 31], [65, 52], [57, 23], [59, 60], [69, 48], [60, 34], [79, 51], [75, 50], [82,
34], [59, 46], [67, 23], [85, 37], [55, 40], [63, 30]]

blood_fat_content = [354, 190, 405, 263, 451, 302, 288, 385, 402, 365, 209, 290, 346, 254,
395, 434, 220, 374, 308, 220, 311, 181, 274, 303, 244]

return t.to_float(weight_age), t.to_float(blood_fat_content)

def inference(X):

return t.matmul(X, W) + b
def loss(X,Y):

Y_predicted = inference(X)

return t.reduce_sum(t.squared_difference(Y, Y_predicted))

def train(total_loss):

learning_rate = 0.0000001

return t.train.GradientDescentOptimizer(learning_rate).minimize(total_loss)

def evaluates(sess, X, Y):

print(sess.run(inference([[80. ,25.]])))

print(sess.run(inference([[65. ,25.]])))

with t.Session() as sess:

t.global_variables_initializer().run()

X, Y = inputs()

total_loss = loss(X, Y)

train_op = train(total_loss)

coord = t.train.Coordinator()

training_steps = 1000

for step in range(training_steps):

sess.run([train_op])

evaluates(sess, X, Y)
coord.request_stop()

sess.close()