六层深度神经网络+SGD+L2正则项+dropout,TensorFlow实现
#NN with SGD, L2
batch_size = 128
layer_cnt = 6#层数
graph = tf.Graph()
with graph.as_default():
# Input data. For the training data, we use a placeholder that will be fed
# at run time with a training minibatch.
tf_train_dataset = tf.placeholder(tf.float32,
shape=(batch_size, image_size * image_size))
tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
tf_valid_dataset = tf.constant(valid_dataset)
tf_test_dataset = tf.constant(test_dataset)
# Variables.
weights = []
biases = []
hidden_cur_cnt = 784
for i in range(layer_cnt - 2):
if hidden_cur_cnt > 2:
hidden_next_cnt = int(hidden_cur_cnt / 2)
else:
hidden_next_cnt = 2
hidden_stddev = np.sqrt(2.0 / hidden_cur_cnt)
weights.append(tf.Variable(tf.truncated_normal([hidden_cur_cnt, hidden_next_cnt], stddev=hidden_stddev)))
biases.append(tf.Variable(tf.zeros([hidden_next_cnt])))
hidden_cur_cnt = hidden_next_cnt
weights.append(tf.Variable(tf.truncated_normal([hidden_cur_cnt, num_labels], stddev=hidden_stddev)))
biases.append(tf.Variable(tf.zeros([num_labels])))
# Training computation.
hidden_drop = tf_train_dataset
keep_prob = 0.5
for i in range(layer_cnt - 2):
y1 = tf.matmul(hidden_drop, weights[i]) + biases[i]
hidden_drop = tf.nn.relu(y1)
keep_prob += 0.5 * i / (layer_cnt + 1)
hidden_drop = tf.nn.dropout(hidden_drop, keep_prob)
z3 = tf.matmul(hidden_drop, weights[-1]) + biases[-1]
l2_loss = tf.Variable(0.0)
for wi in weights:
l2_loss += tf.nn.l2_loss(wi)
loss = tf.reduce_mean(
tf.add(
tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=z3),0.001 * l2_loss) )
# Optimizer.
global_step = tf.Variable(0) # count the number of steps taken.
learning_rate = tf.train.exponential_decay(0.5, global_step, 1000, 0.9)
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
# Predictions for the training, validation, and test data.
train_prediction = tf.nn.softmax(z3)
def predict(dataset):
hidden_drop = dataset
for i in range(layer_cnt - 2):
y1 = tf.matmul(hidden_drop, weights[i]) + biases[i]
hidden_drop = tf.nn.relu(y1)
result = tf.matmul(hidden_drop, weights[-1]) + biases[-1]
return result
valid_prediction = tf.nn.softmax(predict(tf_valid_dataset))
test_prediction = tf.nn.softmax(predict(tf_test_dataset))
运行代码:
num_steps = 20001
with tf.Session(graph=graph) as session:
tf.global_variables_initializer().run()
print("Initialized")
for step in range(num_steps):
# Pick an offset within the training data, which has been randomized.
# Note: we could use better randomization across epochs.
offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
# Generate a minibatch.
batch_data = train_dataset[offset:(offset + batch_size), :]
batch_labels = train_labels[offset:(offset + batch_size), :]
# Prepare a dictionary telling the session where to feed the minibatch.
# The key of the dictionary is the placeholder node of the graph to be fed,
# and the value is the numpy array to feed to it.
feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
_, l, predictions = session.run(
[optimizer, loss, train_prediction], feed_dict=feed_dict)
if (step % 500 == 0):
print("Minibatch loss at step %d: %f" % (step, l))
print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
print("Validation accuracy: %.1f%%" % accuracy(
valid_prediction.eval(), valid_labels))
print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))