Skip to content

Commit 158be77

Browse files
MorvanZhouMorvan Zhou
authored and
Morvan Zhou
committed
update
1 parent 432d7b0 commit 158be77

7 files changed

+35
-92
lines changed

tutorial-contents/401_CNN.py

+8-21
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,7 @@
2626
print(mnist.train.images.shape) # (55000, 28 * 28)
2727
print(mnist.train.labels.shape) # (55000, 10)
2828
plt.imshow(mnist.train.images[0].reshape((28, 28)), cmap='gray')
29-
plt.title('%i' % np.argmax(mnist.train.labels[0]))
30-
plt.show()
29+
plt.title('%i' % np.argmax(mnist.train.labels[0])); plt.show()
3130

3231
tf_x = tf.placeholder(tf.float32, [None, 28*28])
3332
image = tf.reshape(tf_x, [-1, 28, 28, 1]) # (batch, height, width, channel)
@@ -64,25 +63,15 @@
6463

6564
# following function (plot_with_labels) is for visualization, can be ignored if not interested
6665
from matplotlib import cm
67-
try:
68-
from sklearn.manifold import TSNE
69-
HAS_SK = True
70-
except:
71-
HAS_SK = False
66+
try: from sklearn.manifold import TSNE; HAS_SK = True
67+
except: HAS_SK = False; print('\nPlease install sklearn for layer visualization\n')
7268
def plot_with_labels(lowDWeights, labels):
73-
plt.cla()
74-
X, Y = lowDWeights[:, 0], lowDWeights[:, 1]
69+
plt.cla(); X, Y = lowDWeights[:, 0], lowDWeights[:, 1]
7570
for x, y, s in zip(X, Y, labels):
76-
c = cm.rainbow(int(255 * s / 9))
77-
plt.text(x, y, s, backgroundcolor=c, fontsize=9)
78-
plt.xlim(X.min(), X.max())
79-
plt.ylim(Y.min(), Y.max())
80-
plt.title('Visualize last layer')
81-
plt.show()
82-
plt.pause(0.01)
71+
c = cm.rainbow(int(255 * s / 9)); plt.text(x, y, s, backgroundcolor=c, fontsize=9)
72+
plt.xlim(X.min(), X.max()); plt.ylim(Y.min(), Y.max()); plt.title('Visualize last layer'); plt.show(); plt.pause(0.01)
8373

8474
plt.ion()
85-
8675
for step in range(600):
8776
b_x, b_y = mnist.train.next_batch(BATCH_SIZE)
8877
_, loss_ = sess.run([train_op, loss], {tf_x: b_x, tf_y: b_y})
@@ -92,11 +81,9 @@ def plot_with_labels(lowDWeights, labels):
9281

9382
if HAS_SK:
9483
# Visualization of trained flatten layer (T-SNE)
95-
tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
96-
plot_only = 500
84+
tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000); plot_only = 500
9785
low_dim_embs = tsne.fit_transform(flat_representation[:plot_only, :])
98-
labels = np.argmax(test_y, axis=1)[:plot_only]
99-
plot_with_labels(low_dim_embs, labels)
86+
labels = np.argmax(test_y, axis=1)[:plot_only]; plot_with_labels(low_dim_embs, labels)
10087
plt.ioff()
10188

10289
# print 10 predictions from test data

tutorial-contents/403_RNN_regression.py

+7-15
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,9 @@
2020

2121
# show data
2222
steps = np.linspace(0, np.pi*2, 100, dtype=np.float32)
23-
x_np = np.sin(steps) # float32 for converting torch FloatTensor
24-
y_np = np.cos(steps)
25-
plt.plot(steps, y_np, 'r-', label='target (cos)')
26-
plt.plot(steps, x_np, 'b-', label='input (sin)')
27-
plt.legend(loc='best')
28-
plt.show()
23+
x_np = np.sin(steps); y_np = np.cos(steps) # float32 for converting torch FloatTensor
24+
plt.plot(steps, y_np, 'r-', label='target (cos)'); plt.plot(steps, x_np, 'b-', label='input (sin)')
25+
plt.legend(loc='best'); plt.show()
2926

3027
# tensorflow placeholders
3128
tf_x = tf.placeholder(tf.float32, [None, TIME_STEP, INPUT_SIZE]) # shape(batch, 5, 1)
@@ -50,8 +47,7 @@
5047
sess = tf.Session()
5148
sess.run(tf.global_variables_initializer()) # initialize var in graph
5249

53-
plt.figure(1, figsize=(12, 5))
54-
plt.ion() # continuously plot
50+
plt.figure(1, figsize=(12, 5)); plt.ion() # continuously plot
5551

5652
for step in range(60):
5753
start, end = step * np.pi, (step+1)*np.pi # time range
@@ -66,11 +62,7 @@
6662
_, pred_, final_s_ = sess.run([train_op, outs, final_s], feed_dict) # train
6763

6864
# plotting
69-
plt.plot(steps, y.flatten(), 'r-')
70-
plt.plot(steps, pred_.flatten(), 'b-')
71-
plt.ylim((-1.2, 1.2))
72-
plt.draw()
73-
plt.pause(0.05)
65+
plt.plot(steps, y.flatten(), 'r-'); plt.plot(steps, pred_.flatten(), 'b-')
66+
plt.ylim((-1.2, 1.2)); plt.draw(); plt.pause(0.05)
7467

75-
plt.ioff()
76-
plt.show()
68+
plt.ioff(); plt.show()

tutorial-contents/404_AutoEncoder.py

+7-17
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,7 @@
6262
view_data = mnist.test.images[:N_TEST_IMG]
6363
for i in range(N_TEST_IMG):
6464
a[0][i].imshow(np.reshape(view_data[i], (28, 28)), cmap='gray')
65-
a[0][i].set_xticks(())
66-
a[0][i].set_yticks(())
65+
a[0][i].set_xticks(()); a[0][i].set_yticks(())
6766

6867
for step in range(8000):
6968
b_x, b_y = mnist.train.next_batch(BATCH_SIZE)
@@ -76,25 +75,16 @@
7675
for i in range(N_TEST_IMG):
7776
a[1][i].clear()
7877
a[1][i].imshow(np.reshape(decoded_data[i], (28, 28)), cmap='gray')
79-
a[1][i].set_xticks(())
80-
a[1][i].set_yticks(())
81-
plt.draw()
82-
plt.pause(0.01)
83-
78+
a[1][i].set_xticks(()); a[1][i].set_yticks(())
79+
plt.draw(); plt.pause(0.01)
8480
plt.ioff()
8581

8682
# visualize in 3D plot
8783
view_data = test_x[:200]
8884
encoded_data = sess.run(encoded, {tf_x: view_data})
89-
fig = plt.figure(2)
90-
ax = Axes3D(fig)
91-
X = encoded_data[:, 0]
92-
Y = encoded_data[:, 1]
93-
Z = encoded_data[:, 2]
85+
fig = plt.figure(2); ax = Axes3D(fig)
86+
X, Y, Z = encoded_data[:, 0], encoded_data[:, 1], encoded_data[:, 2]
9487
for x, y, z, s in zip(X, Y, Z, test_y):
95-
c = cm.rainbow(int(255*s/9))
96-
ax.text(x, y, z, s, backgroundcolor=c)
97-
ax.set_xlim(X.min(), X.max())
98-
ax.set_ylim(Y.min(), Y.max())
99-
ax.set_zlim(Z.min(), Z.max())
88+
c = cm.rainbow(int(255*s/9)); ax.text(x, y, z, s, backgroundcolor=c)
89+
ax.set_xlim(X.min(), X.max()); ax.set_ylim(Y.min(), Y.max()); ax.set_zlim(Z.min(), Z.max())
10090
plt.show()

tutorial-contents/406_GAN.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,7 @@ def artist_works(): # painting from the famous artist (real target)
7373
plt.plot(PAINT_POINTS[0], 1 * np.power(PAINT_POINTS[0], 2) + 0, c='#FF9359', lw=3, label='lower bound')
7474
plt.text(-.5, 2.3, 'D accuracy=%.2f (0.5 for D to converge)' % pa0.mean(), fontdict={'size': 15})
7575
plt.text(-.5, 2, 'D score= %.2f (-1.38 for G to converge)' % -Dl, fontdict={'size': 15})
76-
plt.ylim((0, 3))
77-
plt.legend(loc='upper right', fontsize=12)
78-
plt.draw()
79-
plt.pause(0.01)
76+
plt.ylim((0, 3)); plt.legend(loc='upper right', fontsize=12); plt.draw(); plt.pause(0.01)
8077

8178
plt.ioff()
8279
plt.show()

tutorial-contents/406_conditional_GAN.py

+2-7
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,7 @@ def artist_works(): # painting from the famous artist (real target)
8080
plt.text(-.5, 2.3, 'D accuracy=%.2f (0.5 for D to converge)' % pa0.mean(), fontdict={'size': 15})
8181
plt.text(-.5, 2, 'D score= %.2f (-1.38 for G to converge)' % -Dl, fontdict={'size': 15})
8282
plt.text(-.5, 1.7, 'Class = %i' % int(labels[0, 0]), fontdict={'size': 15})
83-
plt.ylim((0, 3))
84-
plt.legend(loc='upper right', fontsize=12)
85-
plt.draw()
86-
plt.pause(0.1)
83+
plt.ylim((0, 3)); plt.legend(loc='upper right', fontsize=12); plt.draw(); plt.pause(0.1)
8784

8885
plt.ioff()
8986

@@ -95,6 +92,4 @@ def artist_works(): # painting from the famous artist (real target)
9592
plt.plot(PAINT_POINTS[0], G_paintings[0], c='#4AD631', lw=3, label='G painting for upper class',)
9693
plt.plot(PAINT_POINTS[0], 2 * np.power(PAINT_POINTS[0], 2) + bound[1], c='#74BCFF', lw=3, label='upper bound (class 1)')
9794
plt.plot(PAINT_POINTS[0], 1 * np.power(PAINT_POINTS[0], 2) + bound[0], c='#FF9359', lw=3, label='lower bound (class 1)')
98-
plt.ylim((0, 3))
99-
plt.legend(loc='upper right', fontsize=12)
100-
plt.show()
95+
plt.ylim((0, 3)); plt.legend(loc='upper right', fontsize=12); plt.show()

tutorial-contents/501_dropout.py

+4-9
Original file line numberDiff line numberDiff line change
@@ -69,15 +69,10 @@
6969
o_loss_, d_loss_, o_out_, d_out_ = sess.run(
7070
[o_loss, d_loss, o_out, d_out], {tf_x: test_x, tf_y: test_y, tf_is_training: False} # test, set is_training=False
7171
)
72-
plt.scatter(x, y, c='magenta', s=50, alpha=0.3, label='train')
73-
plt.scatter(test_x, test_y, c='cyan', s=50, alpha=0.3, label='test')
74-
plt.plot(test_x, o_out_, 'r-', lw=3, label='overfitting')
75-
plt.plot(test_x, d_out_, 'b--', lw=3, label='dropout(50%)')
76-
plt.text(0, -1.2, 'overfitting loss=%.4f' % o_loss_, fontdict={'size': 20, 'color': 'red'})
77-
plt.text(0, -1.5, 'dropout loss=%.4f' % d_loss_, fontdict={'size': 20, 'color': 'blue'})
78-
plt.legend(loc='upper left')
79-
plt.ylim((-2.5, 2.5))
80-
plt.pause(0.1)
72+
plt.scatter(x, y, c='magenta', s=50, alpha=0.3, label='train'); plt.scatter(test_x, test_y, c='cyan', s=50, alpha=0.3, label='test')
73+
plt.plot(test_x, o_out_, 'r-', lw=3, label='overfitting'); plt.plot(test_x, d_out_, 'b--', lw=3, label='dropout(50%)')
74+
plt.text(0, -1.2, 'overfitting loss=%.4f' % o_loss_, fontdict={'size': 20, 'color': 'red'}); plt.text(0, -1.5, 'dropout loss=%.4f' % d_loss_, fontdict={'size': 20, 'color': 'blue'})
75+
plt.legend(loc='upper left'); plt.ylim((-2.5, 2.5)); plt.pause(0.1)
8176

8277
plt.ioff()
8378
plt.show()

tutorial-contents/502_batch_normalization.py

+6-19
Original file line numberDiff line numberDiff line change
@@ -86,26 +86,16 @@ def add_layer(self, x, out_size, ac=None):
8686
def plot_histogram(l_in, l_in_bn, pre_ac, pre_ac_bn):
8787
for i, (ax_pa, ax_pa_bn, ax, ax_bn) in enumerate(zip(axs[0, :], axs[1, :], axs[2, :], axs[3, :])):
8888
[a.clear() for a in [ax_pa, ax_pa_bn, ax, ax_bn]]
89-
if i == 0:
90-
p_range = (-7, 10)
91-
the_range = (-7, 10)
92-
else:
93-
p_range = (-4, 4)
94-
the_range = (-1, 1)
89+
if i == 0: p_range = (-7, 10); the_range = (-7, 10)
90+
else: p_range = (-4, 4); the_range = (-1, 1)
9591
ax_pa.set_title('L' + str(i))
9692
ax_pa.hist(pre_ac[i].ravel(), bins=10, range=p_range, color='#FF9359', alpha=0.5)
9793
ax_pa_bn.hist(pre_ac_bn[i].ravel(), bins=10, range=p_range, color='#74BCFF', alpha=0.5)
9894
ax.hist(l_in[i].ravel(), bins=10, range=the_range, color='#FF9359')
9995
ax_bn.hist(l_in_bn[i].ravel(), bins=10, range=the_range, color='#74BCFF')
10096
for a in [ax_pa, ax, ax_pa_bn, ax_bn]:
101-
a.set_yticks(())
102-
a.set_xticks(())
103-
ax_pa_bn.set_xticks(p_range)
104-
ax_bn.set_xticks(the_range)
105-
axs[0, 0].set_ylabel('PreAct')
106-
axs[1, 0].set_ylabel('BN PreAct')
107-
axs[2, 0].set_ylabel('Act')
108-
axs[3, 0].set_ylabel('BN Act')
97+
a.set_yticks(()); a.set_xticks(())
98+
ax_pa_bn.set_xticks(p_range); ax_bn.set_xticks(the_range); axs[2, 0].set_ylabel('Act'); axs[3, 0].set_ylabel('BN Act')
10999
plt.pause(0.01)
110100

111101
losses = [[], []] # record test loss
@@ -137,15 +127,12 @@ def plot_histogram(l_in, l_in_bn, pre_ac, pre_ac_bn):
137127
plt.figure(2)
138128
plt.plot(losses[0], c='#FF9359', lw=3, label='Original')
139129
plt.plot(losses[1], c='#74BCFF', lw=3, label='Batch Normalization')
140-
plt.ylabel('test loss')
141-
plt.ylim((0, 2000))
142-
plt.legend(loc='best')
130+
plt.ylabel('test loss'); plt.ylim((0, 2000)); plt.legend(loc='best')
143131

144132
# plot prediction line
145133
pred, pred_bn = sess.run([nets[0].out, nets[1].out], {tf_x: test_x, tf_is_train: False})
146134
plt.figure(3)
147135
plt.plot(test_x, pred, c='#FF9359', lw=4, label='Original')
148136
plt.plot(test_x, pred_bn, c='#74BCFF', lw=4, label='Batch Normalization')
149137
plt.scatter(x[:200], y[:200], c='r', s=50, alpha=0.2, label='train')
150-
plt.legend(loc='best')
151-
plt.show()
138+
plt.legend(loc='best'); plt.show()

0 commit comments

Comments
 (0)