Skip to content

Commit 0d17fb1

Browse files
committed
Updated chapter 11
1 parent 8ebfa0b commit 0d17fb1

File tree

4 files changed

+30
-30
lines changed

4 files changed

+30
-30
lines changed

11_More_with_TensorFlow/01_Visualizing_Computational_Graphs/01_using_tensorboard.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,21 @@
1111
import numpy as np
1212
import matplotlib.pyplot as plt
1313
import tensorflow as tf
14+
from tensorflow.python.framework import ops
15+
ops.reset_default_graph()
1416

1517
# Initialize a graph session
1618
sess = tf.Session()
1719

1820
# Create a visualizer object
19-
summary_writer = tf.summary.FileWriter('tensorboard', tf.get_default_graph())
21+
summary_writer = tf.summary.FileWriter('tensorboard', sess.graph)
2022

2123
# Create tensorboard folder if not exists
2224
if not os.path.exists('tensorboard'):
2325
os.makedirs('tensorboard')
2426
print('Running a slowed down linear regression. '
2527
'Run the command: $tensorboard --logdir="tensorboard" '
26-
' Then navigate to http://127.0.0.0:6006')
28+
' Then navigate to http://127.0.0.1:6006')
2729

2830
# You can also specify a port option with --port 6006
2931

@@ -69,9 +71,8 @@
6971

7072
# Visualize a histogram (errors)
7173
with tf.name_scope('Loss_and_Residuals'):
72-
tf.summary.histogram('Histogram_Errors', l1_loss)
73-
tf.summary.histogram('Histogram_Residuals', residuals)
74-
74+
tf.summary.histogram('Histogram_Errors', tf.squeeze(l1_loss))
75+
tf.summary.histogram('Histogram_Residuals', tf.squeeze(residuals))
7576

7677

7778
# Declare summary merging operation
@@ -92,7 +93,7 @@
9293
test_loss, test_resids = sess.run([l1_loss, residuals], feed_dict={x_graph_input: x_data_test,
9394
y_graph_input: y_data_test})
9495

95-
if (i+1)%10==0:
96+
if (i + 1) % 10 == 0:
9697
print('Generation {} of {}. Train Loss: {:.3}, Test Loss: {:.3}.'.format(i+1, generations, train_loss, test_loss))
9798

9899
log_writer = tf.summary.FileWriter('tensorboard')
@@ -118,7 +119,7 @@ def gen_linear_plot(slope):
118119
# Add the batch dimension
119120
image = tf.expand_dims(image, 0)
120121
# Add image summary
121-
image_summary_op = tf.summary.image("Linear Plot", image)
122+
image_summary_op = tf.summary.image("Linear_Plot", image)
122123
image_summary = sess.run(image_summary_op)
123124
log_writer.add_summary(image_summary, i)
124-
log_writer.close()
125+
log_writer.close()

11_More_with_TensorFlow/02_Working_with_a_Genetic_Algorithm/02_genetic_algorithm.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@
5858

5959
# Get best fit individual
6060
best_val = tf.reduce_min(top_vals)
61-
best_ind = tf.arg_min(top_vals, 0)
61+
best_ind = tf.argmin(top_vals, 0)
6262
best_individual = tf.gather(population, best_ind)
6363

6464
# Get parents
@@ -108,11 +108,11 @@
108108
best_individual_val = sess.run(best_individual, feed_dict=feed_dict)
109109

110110
if i % 5 == 0:
111-
best_fit = sess.run(best_val, feed_dict = feed_dict)
112-
print('Generation: {}, Best Fitness (lowest MSE): {:.2}'.format(i, -best_fit))
111+
best_fit = sess.run(best_val, feed_dict = feed_dict)
112+
print('Generation: {}, Best Fitness (lowest MSE): {:.2}'.format(i, -best_fit))
113113

114114
plt.plot(truth, label="True Values")
115115
plt.plot(np.squeeze(best_individual_val), label="Best Individual")
116116
plt.axis((0, features, -1.25, 1.25))
117117
plt.legend(loc='upper right')
118-
plt.show()
118+
plt.show()

11_More_with_TensorFlow/03_Clustering_Using_KMeans/03_k_means.py

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323

2424
# Set k-means parameters
2525
# There are 3 types of iris flowers, see if we can predict them
26-
k=3
26+
k = 3
2727
generations = 25
2828

2929
data_points = tf.Variable(iris.data)
@@ -41,9 +41,10 @@
4141
point_matrix = tf.reshape(tf.tile(data_points, [1, k]), [num_pts, k, num_feats])
4242
distances = tf.reduce_sum(tf.square(point_matrix - centroid_matrix), axis=2)
4343

44-
#Find the group it belongs to with tf.argmin()
44+
# Find the group it belongs to with tf.argmin()
4545
centroid_group = tf.argmin(distances, 1)
4646

47+
4748
# Find the group average
4849
def data_group_avg(group_ids, data):
4950
# Sum each group
@@ -52,7 +53,8 @@ def data_group_avg(group_ids, data):
5253
num_total = tf.unsorted_segment_sum(tf.ones_like(data), group_ids, 3)
5354
# Calculate average
5455
avg_by_group = sum_total/num_total
55-
return(avg_by_group)
56+
return avg_by_group
57+
5658

5759
means = data_group_avg(centroid_group, data_points)
5860

@@ -73,18 +75,20 @@ def data_group_avg(group_ids, data):
7375

7476
[centers, assignments] = sess.run([centroids, cluster_labels])
7577

78+
7679
# Find which group assignments correspond to which group labels
7780
# First, need a most common element function
7881
def most_common(my_list):
79-
return(max(set(my_list), key=my_list.count))
82+
return max(set(my_list), key=my_list.count)
83+
8084

8185
label0 = most_common(list(assignments[0:50]))
8286
label1 = most_common(list(assignments[50:100]))
8387
label2 = most_common(list(assignments[100:150]))
8488

85-
group0_count = np.sum(assignments[0:50]==label0)
86-
group1_count = np.sum(assignments[50:100]==label1)
87-
group2_count = np.sum(assignments[100:150]==label2)
89+
group0_count = np.sum(assignments[0:50] == label0)
90+
group1_count = np.sum(assignments[50:100] == label1)
91+
group2_count = np.sum(assignments[100:150] == label2)
8892

8993
accuracy = (group0_count + group1_count + group2_count)/150.
9094

@@ -108,17 +112,15 @@ def most_common(my_list):
108112
# Get k-means classifications for the grid points
109113
xx_pt = list(xx.ravel())
110114
yy_pt = list(yy.ravel())
111-
xy_pts = np.array([[x,y] for x,y in zip(xx_pt, yy_pt)])
115+
xy_pts = np.array([[x, y] for x, y in zip(xx_pt, yy_pt)])
112116
mytree = cKDTree(reduced_centers)
113117
dist, indexes = mytree.query(xy_pts)
114118

115119
# Put the result into a color plot
116120
indexes = indexes.reshape(xx.shape)
117121
plt.figure(1)
118122
plt.clf()
119-
plt.imshow(indexes, interpolation='nearest',
120-
extent=(xx.min(), xx.max(), yy.min(), yy.max()),
121-
cmap=plt.cm.Paired,
123+
plt.imshow(indexes, interpolation='nearest', extent=(xx.min(), xx.max(), yy.min(), yy.max()), cmap=plt.cm.Paired,
122124
aspect='auto', origin='lower')
123125

124126
# Plot each of the true iris data groups
@@ -128,12 +130,9 @@ def most_common(my_list):
128130
temp_group = reduced_data[(i*50):(50)*(i+1)]
129131
plt.plot(temp_group[:, 0], temp_group[:, 1], symbols[i], markersize=10, label=label_name[i])
130132
# Plot the centroids as a white X
131-
plt.scatter(reduced_centers[:, 0], reduced_centers[:, 1],
132-
marker='x', s=169, linewidths=3,
133-
color='w', zorder=10)
134-
plt.title('K-means clustering on Iris Dataset\n'
135-
'Centroids are marked with white cross')
133+
plt.scatter(reduced_centers[:, 0], reduced_centers[:, 1], marker='x', s=169, linewidths=3, color='w', zorder=10)
134+
plt.title('K-means clustering on Iris Dataset Centroids are marked with white cross')
136135
plt.xlim(x_min, x_max)
137136
plt.ylim(y_min, y_max)
138137
plt.legend(loc='lower right')
139-
plt.show()
138+
plt.show()

11_More_with_TensorFlow/04_Solving_A_System_of_ODEs/04_solving_ode_system.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,4 +64,4 @@
6464
plt.plot(prey_values)
6565
plt.plot(predator_values)
6666
plt.legend(['Prey', 'Predator'], loc='upper right')
67-
plt.show()
67+
plt.show()

0 commit comments

Comments
 (0)