Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96144
License: OTHER
1
""" Solution for simple linear regression example using placeholders
2
Created by Chip Huyen ([email protected])
3
CS20: "TensorFlow for Deep Learning Research"
4
cs20.stanford.edu
5
Lecture 03
6
"""
7
import os
8
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
9
import time
10
11
import numpy as np
12
import matplotlib.pyplot as plt
13
import tensorflow as tf
14
15
import utils
16
17
DATA_FILE = 'data/birth_life_2010.txt'
18
19
# Step 1: read in data from the .txt file
20
data, n_samples = utils.read_birth_life_data(DATA_FILE)
21
22
# Step 2: create placeholders for X (birth rate) and Y (life expectancy)
23
X = tf.placeholder(tf.float32, name='X')
24
Y = tf.placeholder(tf.float32, name='Y')
25
26
# Step 3: create weight and bias, initialized to 0
27
w = tf.get_variable('weights', initializer=tf.constant(0.0))
28
b = tf.get_variable('bias', initializer=tf.constant(0.0))
29
30
# Step 4: build model to predict Y
31
Y_predicted = w * X + b
32
33
# Step 5: use the squared error as the loss function
34
# you can use either mean squared error or Huber loss
35
loss = tf.square(Y - Y_predicted, name='loss')
36
# loss = utils.huber_loss(Y, Y_predicted)
37
38
# Step 6: using gradient descent with learning rate of 0.001 to minimize loss
39
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss)
40
41
42
start = time.time()
43
writer = tf.summary.FileWriter('./graphs/linear_reg', tf.get_default_graph())
44
with tf.Session() as sess:
45
# Step 7: initialize the necessary variables, in this case, w and b
46
sess.run(tf.global_variables_initializer())
47
48
# Step 8: train the model for 100 epochs
49
for i in range(100):
50
total_loss = 0
51
for x, y in data:
52
# Session execute optimizer and fetch values of loss
53
_, l = sess.run([optimizer, loss], feed_dict={X: x, Y:y})
54
total_loss += l
55
print('Epoch {0}: {1}'.format(i, total_loss/n_samples))
56
57
# close the writer when you're done using it
58
writer.close()
59
60
# Step 9: output the values of w and b
61
w_out, b_out = sess.run([w, b])
62
63
print('Took: %f seconds' %(time.time() - start))
64
65
# plot the results
66
plt.plot(data[:,0], data[:,1], 'bo', label='Real data')
67
plt.plot(data[:,0], data[:,0] * w_out + b_out, 'r', label='Predicted data')
68
plt.legend()
69
plt.show()
70