-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
304_optimizer.py
69 lines (57 loc) · 1.9 KB
/
304_optimizer.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
62
63
64
65
66
67
68
69
"""
Know more, visit my Python tutorial page: https://morvanzhou.github.io/tutorials/
My Youtube Channel: https://www.youtube.com/user/MorvanZhou
Dependencies:
tensorflow: 1.1.0
matplotlib
numpy
"""
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
tf.set_random_seed(1)
np.random.seed(1)
LR = 0.01
BATCH_SIZE = 32
# fake data
x = np.linspace(-1, 1, 100)[:, np.newaxis] # shape (100, 1)
noise = np.random.normal(0, 0.1, size=x.shape)
y = np.power(x, 2) + noise # shape (100, 1) + some noise
# plot dataset
plt.scatter(x, y)
plt.show()
# default network
class Net:
def __init__(self, opt, **kwargs):
self.x = tf.placeholder(tf.float32, [None, 1])
self.y = tf.placeholder(tf.float32, [None, 1])
l = tf.layers.dense(self.x, 20, tf.nn.relu)
out = tf.layers.dense(l, 1)
self.loss = tf.losses.mean_squared_error(self.y, out)
self.train = opt(LR, **kwargs).minimize(self.loss)
# different nets
net_SGD = Net(tf.train.GradientDescentOptimizer)
net_Momentum = Net(tf.train.MomentumOptimizer, momentum=0.9)
net_RMSprop = Net(tf.train.RMSPropOptimizer)
net_Adam = Net(tf.train.AdamOptimizer)
nets = [net_SGD, net_Momentum, net_RMSprop, net_Adam]
sess = tf.Session()
sess.run(tf.global_variables_initializer())
losses_his = [[], [], [], []] # record loss
# training
for step in range(300): # for each training step
index = np.random.randint(0, x.shape[0], BATCH_SIZE)
b_x = x[index]
b_y = y[index]
for net, l_his in zip(nets, losses_his):
_, l = sess.run([net.train, net.loss], {net.x: b_x, net.y: b_y})
l_his.append(l) # loss recoder
# plot loss history
labels = ['SGD', 'Momentum', 'RMSprop', 'Adam']
for i, l_his in enumerate(losses_his):
plt.plot(l_his, label=labels[i])
plt.legend(loc='best')
plt.xlabel('Steps')
plt.ylabel('Loss')
plt.ylim((0, 0.2))
plt.show()