📚 The CoCalc Library - books, templates and other resources
License: OTHER
""" Simple linear regression example in TensorFlow1This program tries to predict the number of thefts from2the number of fire in the city of Chicago3Author: Chip Huyen4Prepared for the class CS 20SI: "TensorFlow for Deep Learning Research"5cs20si.stanford.edu6"""7import os8os.environ['TF_CPP_MIN_LOG_LEVEL']='2'910import numpy as np11import matplotlib.pyplot as plt12import tensorflow as tf13import xlrd1415import utils1617DATA_FILE = 'data/fire_theft.xls'1819# Step 1: read in data from the .xls file20book = xlrd.open_workbook(DATA_FILE, encoding_override="utf-8")21sheet = book.sheet_by_index(0)22data = np.asarray([sheet.row_values(i) for i in range(1, sheet.nrows)])23n_samples = sheet.nrows - 12425# Step 2: create placeholders for input X (number of fire) and label Y (number of theft)26X = tf.placeholder(tf.float32, name='X')27Y = tf.placeholder(tf.float32, name='Y')2829# Step 3: create weight and bias, initialized to 030w = tf.Variable(0.0, name='weights')31b = tf.Variable(0.0, name='bias')3233# Step 4: build model to predict Y34Y_predicted = X * w + b3536# Step 5: use the square error as the loss function37loss = tf.square(Y - Y_predicted, name='loss')38# loss = utils.huber_loss(Y, Y_predicted)3940# Step 6: using gradient descent with learning rate of 0.01 to minimize loss41optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss)4243with tf.Session() as sess:44# Step 7: initialize the necessary variables, in this case, w and b45sess.run(tf.global_variables_initializer())4647writer = tf.summary.FileWriter('./graphs/linear_reg', sess.graph)4849# Step 8: train the model50for i in range(50): # train the model 100 epochs51total_loss = 052for x, y in data:53# Session runs train_op and fetch values of loss54_, l = sess.run([optimizer, loss], feed_dict={X: x, Y:y})55total_loss += l56print('Epoch {0}: {1}'.format(i, total_loss/n_samples))5758# close the writer when you're done using it59writer.close()6061# Step 9: output the values of w and b62w, b = sess.run([w, b])6364# plot the results65X, Y = data.T[0], data.T[1]66plt.plot(X, Y, 'bo', label='Real data')67plt.plot(X, X * w + b, 'r', label='Predicted data')68plt.legend()69plt.show()7071