In [1]:
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import seaborn as sns
import xlrd
In [2]:
DATA_FILE = "../data/fire_theft.xls"
In [3]:
book = xlrd.open_workbook(DATA_FILE, encoding_override="utf-8")
sheet = book.sheet_by_index(0)
data = np.asarray([sheet.row_values(i) for i in range(1, sheet.nrows)])
n_samples = sheet.nrows - 1
In [4]:
data[:10]
Out[4]:
In [5]:
X = tf.placeholder(tf.float32, name='X')
Y = tf.placeholder(tf.float32, name='Y')
w = tf.Variable(0.0, name="weights")
b = tf.Variable(0.0, name="bias")
Y_predicted = X * w + b
loss = tf.square(Y - Y_predicted, name='loss')
optimizer = tf.train.GradientDescentOptimizer(learning_rate=.001).minimize(loss)
In [6]:
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
writer = tf.summary.FileWriter('../graphs/linear_reg', sess.graph)
# 100 epochs
for i in range(100):
total_loss = 0
for x, y in data:
_, l = sess.run([optimizer, loss], {X: x, Y: y})
total_loss += l
if not i % 20:
print('Epoch {0}: {1}'.format(i, total_loss))
writer.close()
w, b = sess.run([w, b])
print('After training, w is {0}, b is {1}'.format(w, b))
In [7]:
%matplotlib inline
X, Y = data.T[0], data.T[1]
plt.plot(X, Y, 'bo', label='Real Data')
plt.plot(X, X * w + b, 'r', label='Predicted Data')
plt.legend()
plt.show()
In [ ]: