A TensorFlow very (very…) simple Linear Regression model
How to train a TensorFlow linear regression model to fit data
About myself
https://github.com/caballerofelipe
https://medium.com/@felipecaballero
https://www.linkedin.com/in/felipe-caballero-74578412/
A TensorFlow very simple Linear Regression model
Objectives
A TensorFlow very simple Linear Regression model
WTF is Linear Regression?
A TensorFlow very simple Linear Regression model
How to estimate a function using Linear Regression?
The idea of cost minimization is used a lot in Machine Learning.
A TensorFlow very simple Linear Regression model
Minimize cost using Gradient Descent
Image from https://flylib.com/books/2/71/1/html/2/files/17fig06.gif
A TensorFlow very simple Linear Regression model
Ok, so… how do we do it?
A TensorFlow very simple Linear Regression model
Install stuff
Activate
Test
Create dir
Create file
Prepare the environment
$ conda create -n envName python=3.6 tensorflow matplotlib jupyter
$ source activate envName
(envName) $ python --version
(envName) $ mkdir linreg
(envName) $ cd linreg
(envName) $ touch main.py
A TensorFlow very simple Linear Regression model
Importing Libraries
# Prepare stuff
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
# To be used in Jupyter Notebooks
from tensorflow.python.framework import ops
A TensorFlow very simple Linear Regression model
Disable warning
import os
# See https://stackoverflow.com/a/47227886/1071459
# Just disables the warning, doesn't enable AVX/FMA
# To avoid tensorflow warnings, uncomment the following line
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
A TensorFlow very simple Linear Regression model
Prepare the data
# Prepare the data
x = np.array([
-7, 5, 7, 12, 2,
4, 5, 6, 19, 14,
16, 15, 11, 8, 18,
-2, 14, 17, 7, 17
])
y = np.array([
-7.56, 21.01, 29.11, 47.89, 14.11,
16.69, 29.81, 28.67, 63.94, 54.8,
49.65, 52.26, 44.86, 40.45, 70.92,
-0.37, 44.34, 64.27, 32.85, 50.14
])
A TensorFlow very simple Linear Regression model
Check the data
# Check the data
print('x.shape():')
print(x.shape)
print('y.shape():')
print(y.shape)
input("Press enter to continue...")
plt.scatter(x, y)
plt.show()
A TensorFlow very simple Linear Regression model
The TensorFlow part — Config
# TensorFlow Model
# Config
num_epochs = 1000
learning_rate = 0.001
# /Config
A TensorFlow very simple Linear Regression model
The TensorFlow part — If using Jupyter
# This is necessary if the code is run inside Jupyter
ops.reset_default_graph()
A TensorFlow very simple Linear Regression model
The TensorFlow part — The graph
# Creating the graph
X = tf.placeholder(tf.float32, name='X')
Y = tf.placeholder(tf.float32, name='Y')
a = tf.get_variable('a', initializer=0.)
b = tf.get_variable('b', initializer=0.)
h = a * X + b
cost = tf.reduce_mean( (h - Y)**2 )
optimizer = tf.train.GradientDescentOptimizer(
learning_rate=learning_rate
).minimize(cost)
init = tf.global_variables_initializer()
A TensorFlow very simple Linear Regression model
Run the model — Store result in vars
# Running the Model
found_a = 0
found_b = 0
A TensorFlow very simple Linear Regression model
Run the model — The actual run
with tf.Session() as sess:
sess.run(init)
for epoch in range(num_epochs):
_, costValue = sess.run(
[optimizer, cost],
feed_dict={
X: x,
Y: y,
}
)
found_a = a.eval()
found_b = b.eval()
if epoch % (num_epochs/10) == 0: # Every 10 percent
print("... epoch: " + str(epoch))
print(f"cost[{str(costValue)}] / a[{str(a.eval())}] / b[{str(b.eval())}]")
A TensorFlow very simple Linear Regression model
Visualize the results
# Seeing the obtained values in a plot
xrange = np.linspace(-10, 30, 2)
# Plot points
plt.plot(x, y, 'ro')
# Plot resulting function
plt.plot(xrange, xrange * found_a + found_b, 'b')
plt.show()
A TensorFlow very simple Linear Regression model
Possible growth — …to enhance the code
We could:
A TensorFlow very simple Linear Regression model