📚 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# Phase 1: Assemble the graph20# Step 1: read in data from the .xls file21book = xlrd.open_workbook(DATA_FILE, encoding_override='utf-8')22sheet = book.sheet_by_index(0)23data = np.asarray([sheet.row_values(i) for i in range(1, sheet.nrows)])24n_samples = sheet.nrows - 12526# Step 2: create placeholders for input X (number of fire) and label Y (number of theft)27# Both have the type float32282930# Step 3: create weight and bias, initialized to 031# name your variables w and b323334# Step 4: predict Y (number of theft) from the number of fire35# name your variable Y_predicted363738# Step 5: use the square error as the loss function39# name your variable loss404142# Step 6: using gradient descent with learning rate of 0.01 to minimize loss4344# Phase 2: Train our model45with tf.Session() as sess:46# Step 7: initialize the necessary variables, in this case, w and b47# TO - DO484950# Step 8: train the model51for i in range(50): # run 100 epochs52total_loss = 053for x, y in data:54# Session runs optimizer to minimize loss and fetch the value of loss. Name the received value as l55# TO DO: write sess.run()5657total_loss += l58print("Epoch {0}: {1}".format(i, total_loss/n_samples))5960# plot the results61# X, Y = data.T[0], data.T[1]62# plt.plot(X, Y, 'bo', label='Real data')63# plt.plot(X, X * w + b, 'r', label='Predicted data')64# plt.legend()65# plt.show()6667