Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132926 views
License: OTHER
1
""" Simple linear regression example in TensorFlow
2
This program tries to predict the number of thefts from
3
the number of fire in the city of Chicago
4
Author: Chip Huyen
5
Prepared for the class CS 20SI: "TensorFlow for Deep Learning Research"
6
cs20si.stanford.edu
7
"""
8
import os
9
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
10
11
import numpy as np
12
import matplotlib.pyplot as plt
13
import tensorflow as tf
14
import xlrd
15
16
import utils
17
18
DATA_FILE = 'data/fire_theft.xls'
19
20
# Phase 1: Assemble the graph
21
# Step 1: read in data from the .xls file
22
book = xlrd.open_workbook(DATA_FILE, encoding_override='utf-8')
23
sheet = book.sheet_by_index(0)
24
data = np.asarray([sheet.row_values(i) for i in range(1, sheet.nrows)])
25
n_samples = sheet.nrows - 1
26
27
# Step 2: create placeholders for input X (number of fire) and label Y (number of theft)
28
# Both have the type float32
29
30
31
# Step 3: create weight and bias, initialized to 0
32
# name your variables w and b
33
34
35
# Step 4: predict Y (number of theft) from the number of fire
36
# name your variable Y_predicted
37
38
39
# Step 5: use the square error as the loss function
40
# name your variable loss
41
42
43
# Step 6: using gradient descent with learning rate of 0.01 to minimize loss
44
45
# Phase 2: Train our model
46
with tf.Session() as sess:
47
# Step 7: initialize the necessary variables, in this case, w and b
48
# TO - DO
49
50
51
# Step 8: train the model
52
for i in range(50): # run 100 epochs
53
total_loss = 0
54
for x, y in data:
55
# Session runs optimizer to minimize loss and fetch the value of loss. Name the received value as l
56
# TO DO: write sess.run()
57
58
total_loss += l
59
print("Epoch {0}: {1}".format(i, total_loss/n_samples))
60
61
# plot the results
62
# X, Y = data.T[0], data.T[1]
63
# plt.plot(X, Y, 'bo', label='Real data')
64
# plt.plot(X, X * w + b, 'r', label='Predicted data')
65
# plt.legend()
66
# plt.show()
67