-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path01_multivar_linear_regression_starter.py
61 lines (49 loc) · 1.8 KB
/
01_multivar_linear_regression_starter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""
Simple linear regression example in TensorFlow
This program tries to predict the final test score
of general psychology based on previous exam scores
"""
import numpy as np
import tensorflow as tf
import csv
DATA_FILE = 'data/test_scores.csv'
# Step 1: read data
with open(DATA_FILE, 'r') as f:
data = []
reader = csv.reader(f, delimiter=',')
for i, row in enumerate(reader):
if i == 0:
continue
data.append(row)
n_samples = len(data)
data = np.asarray(data, dtype='float32')
# Step 2: create placeholders
# YOUR CODE HERE
# Step 3: create weight and bias
# YOUR CODE HERE
# Step 4: build model to predict Y
# YOUR CODE HERE
# Step 5: use the square error as the loss function
loss = tf.reduce_mean(tf.square(Y - Y_predicted, name='loss'))
# Step 6: using gradient descent with learning rate of 0.01 to minimize loss
optimizer = tf.train.GradientDescentOptimizer(learning_rate=2e-7)
train = optimizer.minimize(loss)
with tf.Session() as sess:
# Step 7: initialize the necessary variables, in this case, w and b
sess.run(tf.global_variables_initializer())
# Step 8: train the model
for i in range(100): # train the model 100 times
total_loss = 0
for x1, x2, x3, y in data:
# Session runs train_op and fetch values of loss
# YOUR CODE HERE
total_loss += l
print('Epoch {0}: {1}'.format(i, total_loss / n_samples))
# Step 9: output the values of w and b
W_value, b_value = sess.run([W, b])
# predict
for i in [2, 13, 18]:
y_h = sess.run(Y_predicted, feed_dict={X: np.expand_dims(data[i][:-1], 0)})
print('X1: {}, X2: {}, X3: {}'.format(data[i][0], data[i][1], data[i][2]))
print('Y_predicted: {}'.format(np.squeeze(y_h)))
print('Y: {}'.format(data[i][-1]))