MCPcopy Index your code
hub / github.com/lazyprogrammer/machine_learning_examples / main

Function main

cnn_class/benchmark.py:63–142  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

61
62
63def main():
64 train, test = get_data()
65
66
67 # Need to scale! don't leave as 0..255
68 # Y is a N x 1 matrix with values 1..10 (MATLAB indexes by 1)
69 # So flatten it and make it 0..9
70 # Also need indicator matrix for cost calculation
71 Xtrain = flatten(train['X'].astype(np.float32) / 255.)
72 Ytrain = train['y'].flatten() - 1
73 Xtrain, Ytrain = shuffle(Xtrain, Ytrain)
74
75 Xtest = flatten(test['X'].astype(np.float32) / 255.)
76 Ytest = test['y'].flatten() - 1
77
78 # gradient descent params
79 max_iter = 20
80 print_period = 10
81 N, D = Xtrain.shape
82 batch_sz = 500
83 n_batches = N // batch_sz
84
85 # initial weights
86 M1 = 1000 # hidden layer size
87 M2 = 500
88 K = 10
89 W1_init = np.random.randn(D, M1) / np.sqrt(D + M1)
90 b1_init = np.zeros(M1)
91 W2_init = np.random.randn(M1, M2) / np.sqrt(M1 + M2)
92 b2_init = np.zeros(M2)
93 W3_init = np.random.randn(M2, K) / np.sqrt(M2 + K)
94 b3_init = np.zeros(K)
95
96 # define variables and expressions
97 X = tf.placeholder(tf.float32, shape=(None, D), name='X')
98 T = tf.placeholder(tf.int32, shape=(None,), name='T')
99 W1 = tf.Variable(W1_init.astype(np.float32))
100 b1 = tf.Variable(b1_init.astype(np.float32))
101 W2 = tf.Variable(W2_init.astype(np.float32))
102 b2 = tf.Variable(b2_init.astype(np.float32))
103 W3 = tf.Variable(W3_init.astype(np.float32))
104 b3 = tf.Variable(b3_init.astype(np.float32))
105
106 Z1 = tf.nn.relu( tf.matmul(X, W1) + b1 )
107 Z2 = tf.nn.relu( tf.matmul(Z1, W2) + b2 )
108 logits = tf.matmul(Z2, W3) + b3
109
110 cost = tf.reduce_sum(
111 tf.nn.sparse_softmax_cross_entropy_with_logits(
112 logits=logits,
113 labels=T
114 )
115 )
116
117 train_op = tf.train.RMSPropOptimizer(0.0001, decay=0.99, momentum=0.9).minimize(cost)
118
119 # we'll use this to calculate the error rate
120 predict_op = tf.argmax(logits, 1)

Callers 1

benchmark.pyFile · 0.70

Calls 4

get_dataFunction · 0.70
flattenFunction · 0.70
error_rateFunction · 0.70
runMethod · 0.45

Tested by

no test coverage detected