mirror of
https://github.com/wassname/ray.git
synced 2026-08-12 12:20:11 +08:00
Clean up top level Ray dir (#5404)
This commit is contained in:
@@ -0,0 +1,154 @@
|
||||
from __future__ import absolute_import
|
||||
from __future__ import division
|
||||
from __future__ import print_function
|
||||
|
||||
import argparse
|
||||
from collections import defaultdict
|
||||
import numpy as np
|
||||
import ray
|
||||
|
||||
from tensorflow.examples.tutorials.mnist import input_data
|
||||
|
||||
import objective
|
||||
|
||||
parser = argparse.ArgumentParser(description="Run the hyperparameter "
|
||||
"optimization example.")
|
||||
parser.add_argument("--num-starting-segments", default=5, type=int,
|
||||
help="The number of training segments to start in "
|
||||
"parallel.")
|
||||
parser.add_argument("--num-segments", default=10, type=int,
|
||||
help="The number of additional training segments to "
|
||||
"perform.")
|
||||
parser.add_argument("--steps-per-segment", default=20, type=int,
|
||||
help="The number of steps of training to do per training "
|
||||
"segment.")
|
||||
parser.add_argument("--redis-address", default=None, type=str,
|
||||
help="The Redis address of the cluster.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
args = parser.parse_args()
|
||||
|
||||
ray.init(redis_address=args.redis_address)
|
||||
|
||||
# The number of training passes over the dataset to use for network.
|
||||
steps = args.steps_per_segment
|
||||
|
||||
# Load the mnist data and turn the data into remote objects.
|
||||
print("Downloading the MNIST dataset. This may take a minute.")
|
||||
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
|
||||
train_images = ray.put(mnist.train.images)
|
||||
train_labels = ray.put(mnist.train.labels)
|
||||
validation_images = ray.put(mnist.validation.images)
|
||||
validation_labels = ray.put(mnist.validation.labels)
|
||||
|
||||
# Keep track of the accuracies that we've seen at different numbers of
|
||||
# iterations.
|
||||
accuracies_by_num_steps = defaultdict(lambda: [])
|
||||
|
||||
# Define a method to determine if an experiment looks promising or not.
|
||||
def is_promising(experiment_info):
|
||||
accuracies = experiment_info["accuracies"]
|
||||
total_num_steps = experiment_info["total_num_steps"]
|
||||
comparable_accuracies = accuracies_by_num_steps[total_num_steps]
|
||||
if len(comparable_accuracies) == 0:
|
||||
if len(accuracies) == 1:
|
||||
# This means that we haven't seen anything finish yet, so keep
|
||||
# running this experiment.
|
||||
return True
|
||||
else:
|
||||
# The experiment is promising if the second half of the
|
||||
# accuracies are better than the first half of the accuracies.
|
||||
return (np.mean(accuracies[:len(accuracies) // 2]) <
|
||||
np.mean(accuracies[len(accuracies) // 2:]))
|
||||
# Otherwise, continue running the experiment if it is in the top half
|
||||
# of experiments we've seen so far at this point in time.
|
||||
return np.mean(accuracy > np.array(comparable_accuracies)) > 0.5
|
||||
|
||||
# Keep track of all of the experiment segments that we're running. This
|
||||
# dictionary uses the object ID of the experiment as the key.
|
||||
experiment_info = {}
|
||||
# Keep track of the curently running experiment IDs.
|
||||
remaining_ids = []
|
||||
|
||||
# Keep track of the best hyperparameters and the best accuracy.
|
||||
best_hyperparameters = None
|
||||
best_accuracy = 0
|
||||
|
||||
# A function for generating random hyperparameters.
|
||||
def generate_hyperparameters():
|
||||
return {"learning_rate": 10 ** np.random.uniform(-5, 5),
|
||||
"batch_size": np.random.randint(1, 100),
|
||||
"dropout": np.random.uniform(0, 1),
|
||||
"stddev": 10 ** np.random.uniform(-5, 5)}
|
||||
|
||||
# Launch some initial experiments.
|
||||
for _ in range(args.num_starting_segments):
|
||||
hyperparameters = generate_hyperparameters()
|
||||
experiment_id = objective.train_cnn_and_compute_accuracy.remote(
|
||||
hyperparameters, steps, train_images, train_labels,
|
||||
validation_images, validation_labels)
|
||||
experiment_info[experiment_id] = {"hyperparameters": hyperparameters,
|
||||
"total_num_steps": steps,
|
||||
"accuracies": []}
|
||||
remaining_ids.append(experiment_id)
|
||||
|
||||
for _ in range(args.num_segments):
|
||||
# Wait for a segment of an experiment to finish.
|
||||
ready_ids, remaining_ids = ray.wait(remaining_ids, num_returns=1)
|
||||
experiment_id = ready_ids[0]
|
||||
# Get the accuracy and the weights.
|
||||
accuracy, weights = ray.get(experiment_id)
|
||||
# Update the experiment info.
|
||||
previous_info = experiment_info[experiment_id]
|
||||
previous_info["accuracies"].append(accuracy)
|
||||
|
||||
# Update the best accuracy and best hyperparameters.
|
||||
if accuracy > best_accuracy:
|
||||
best_hyperparameters = previous_info["hyperparameters"]
|
||||
best_accuracy = accuracy
|
||||
|
||||
if is_promising(previous_info):
|
||||
# If the experiment still looks promising, then continue running
|
||||
# it.
|
||||
print("Continuing to run the experiment with hyperparameters {}."
|
||||
.format(previous_info["hyperparameters"]))
|
||||
new_hyperparameters = previous_info["hyperparameters"]
|
||||
new_info = {"hyperparameters": new_hyperparameters,
|
||||
"total_num_steps": (previous_info["total_num_steps"] +
|
||||
steps),
|
||||
"accuracies": previous_info["accuracies"][:]}
|
||||
starting_weights = weights
|
||||
else:
|
||||
# If the experiment does not look promising, start a new
|
||||
# experiment.
|
||||
print("Ending the experiment with hyperparameters {}."
|
||||
.format(previous_info["hyperparameters"]))
|
||||
new_hyperparameters = generate_hyperparameters()
|
||||
new_info = {"hyperparameters": new_hyperparameters,
|
||||
"total_num_steps": steps,
|
||||
"accuracies": []}
|
||||
starting_weights = None
|
||||
|
||||
# Start running the next segment.
|
||||
new_experiment_id = objective.train_cnn_and_compute_accuracy.remote(
|
||||
new_hyperparameters, steps, train_images, train_labels,
|
||||
validation_images, validation_labels, weights=starting_weights)
|
||||
experiment_info[new_experiment_id] = new_info
|
||||
remaining_ids.append(new_experiment_id)
|
||||
|
||||
# Update the set of all accuracies that we've seen.
|
||||
accuracies_by_num_steps[previous_info["total_num_steps"]].append(
|
||||
accuracy)
|
||||
|
||||
# Record the best performing set of hyperparameters.
|
||||
print("""Best accuracy was {:.3} with
|
||||
learning_rate: {:.2}
|
||||
batch_size: {}
|
||||
dropout: {:.2}
|
||||
stddev: {:.2}
|
||||
""".format(100 * best_accuracy,
|
||||
best_hyperparameters["learning_rate"],
|
||||
best_hyperparameters["batch_size"],
|
||||
best_hyperparameters["dropout"],
|
||||
best_hyperparameters["stddev"]))
|
||||
@@ -0,0 +1,100 @@
|
||||
from __future__ import absolute_import
|
||||
from __future__ import division
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
import ray
|
||||
import argparse
|
||||
|
||||
from tensorflow.examples.tutorials.mnist import input_data
|
||||
|
||||
import objective
|
||||
|
||||
parser = argparse.ArgumentParser(description="Run the hyperparameter "
|
||||
"optimization example.")
|
||||
parser.add_argument("--trials", default=2, type=int,
|
||||
help="The number of random trials to do.")
|
||||
parser.add_argument("--steps", default=10, type=int,
|
||||
help="The number of steps of training to do per network.")
|
||||
parser.add_argument("--redis-address", default=None, type=str,
|
||||
help="The Redis address of the cluster.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
args = parser.parse_args()
|
||||
|
||||
ray.init(redis_address=args.redis_address)
|
||||
|
||||
# The number of sets of random hyperparameters to try.
|
||||
trials = args.trials
|
||||
# The number of training passes over the dataset to use for network.
|
||||
steps = args.steps
|
||||
|
||||
# Load the mnist data and turn the data into remote objects.
|
||||
print("Downloading the MNIST dataset. This may take a minute.")
|
||||
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
|
||||
train_images = ray.put(mnist.train.images)
|
||||
train_labels = ray.put(mnist.train.labels)
|
||||
validation_images = ray.put(mnist.validation.images)
|
||||
validation_labels = ray.put(mnist.validation.labels)
|
||||
|
||||
# Keep track of the best hyperparameters and the best accuracy.
|
||||
best_hyperparameters = None
|
||||
best_accuracy = 0
|
||||
# This list holds the object IDs for all of the experiments that we have
|
||||
# launched and that have not yet been processed.
|
||||
remaining_ids = []
|
||||
# This is a dictionary mapping the object ID of an experiment to the
|
||||
# hyerparameters used for that experiment.
|
||||
hyperparameters_mapping = {}
|
||||
|
||||
# A function for generating random hyperparameters.
|
||||
def generate_hyperparameters():
|
||||
return {"learning_rate": 10 ** np.random.uniform(-5, 5),
|
||||
"batch_size": np.random.randint(1, 100),
|
||||
"dropout": np.random.uniform(0, 1),
|
||||
"stddev": 10 ** np.random.uniform(-5, 5)}
|
||||
|
||||
# Randomly generate some hyperparameters, and launch a task for each set.
|
||||
for i in range(trials):
|
||||
hyperparameters = generate_hyperparameters()
|
||||
accuracy_id = objective.train_cnn_and_compute_accuracy.remote(
|
||||
hyperparameters, steps, train_images, train_labels,
|
||||
validation_images, validation_labels)
|
||||
remaining_ids.append(accuracy_id)
|
||||
# Keep track of which hyperparameters correspond to this experiment.
|
||||
hyperparameters_mapping[accuracy_id] = hyperparameters
|
||||
|
||||
# Fetch and print the results of the tasks in the order that they complete.
|
||||
for i in range(trials):
|
||||
# Use ray.wait to get the object ID of the first task that completes.
|
||||
ready_ids, remaining_ids = ray.wait(remaining_ids)
|
||||
# Process the output of this task.
|
||||
result_id = ready_ids[0]
|
||||
hyperparameters = hyperparameters_mapping[result_id]
|
||||
accuracy, _ = ray.get(result_id)
|
||||
print("""We achieve accuracy {:.3}% with
|
||||
learning_rate: {:.2}
|
||||
batch_size: {}
|
||||
dropout: {:.2}
|
||||
stddev: {:.2}
|
||||
""".format(100 * accuracy,
|
||||
hyperparameters["learning_rate"],
|
||||
hyperparameters["batch_size"],
|
||||
hyperparameters["dropout"],
|
||||
hyperparameters["stddev"]))
|
||||
if accuracy > best_accuracy:
|
||||
best_hyperparameters = hyperparameters
|
||||
best_accuracy = accuracy
|
||||
|
||||
# Record the best performing set of hyperparameters.
|
||||
print("""Best accuracy over {} trials was {:.3} with
|
||||
learning_rate: {:.2}
|
||||
batch_size: {}
|
||||
dropout: {:.2}
|
||||
stddev: {:.2}
|
||||
""".format(trials, 100 * best_accuracy,
|
||||
best_hyperparameters["learning_rate"],
|
||||
best_hyperparameters["batch_size"],
|
||||
best_hyperparameters["dropout"],
|
||||
best_hyperparameters["stddev"]))
|
||||
@@ -0,0 +1,127 @@
|
||||
# Most of the tensorflow code is adapted from Tensorflow's tutorial on using
|
||||
# CNNs to train MNIST
|
||||
# https://www.tensorflow.org/versions/r0.9/tutorials/mnist/pros/index.html#build-a-multilayer-convolutional-network. # noqa: E501
|
||||
|
||||
from __future__ import absolute_import
|
||||
from __future__ import division
|
||||
from __future__ import print_function
|
||||
|
||||
import tensorflow as tf
|
||||
|
||||
import ray
|
||||
import ray.experimental.tf_utils
|
||||
|
||||
|
||||
def get_batch(data, batch_index, batch_size):
|
||||
# This method currently drops data when num_data is not divisible by
|
||||
# batch_size.
|
||||
num_data = data.shape[0]
|
||||
num_batches = num_data // batch_size
|
||||
batch_index %= num_batches
|
||||
return data[(batch_index * batch_size):((batch_index + 1) * batch_size)]
|
||||
|
||||
|
||||
def weight(shape, stddev):
|
||||
initial = tf.truncated_normal(shape, stddev=stddev)
|
||||
return tf.Variable(initial)
|
||||
|
||||
|
||||
def bias(shape):
|
||||
initial = tf.constant(0.1, shape=shape)
|
||||
return tf.Variable(initial)
|
||||
|
||||
|
||||
def conv2d(x, W):
|
||||
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding="SAME")
|
||||
|
||||
|
||||
def max_pool_2x2(x):
|
||||
return tf.nn.max_pool(
|
||||
x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")
|
||||
|
||||
|
||||
def cnn_setup(x, y, keep_prob, lr, stddev):
|
||||
first_hidden = 32
|
||||
second_hidden = 64
|
||||
fc_hidden = 1024
|
||||
W_conv1 = weight([5, 5, 1, first_hidden], stddev)
|
||||
B_conv1 = bias([first_hidden])
|
||||
x_image = tf.reshape(x, [-1, 28, 28, 1])
|
||||
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + B_conv1)
|
||||
h_pool1 = max_pool_2x2(h_conv1)
|
||||
W_conv2 = weight([5, 5, first_hidden, second_hidden], stddev)
|
||||
b_conv2 = bias([second_hidden])
|
||||
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
|
||||
h_pool2 = max_pool_2x2(h_conv2)
|
||||
W_fc1 = weight([7 * 7 * second_hidden, fc_hidden], stddev)
|
||||
b_fc1 = bias([fc_hidden])
|
||||
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * second_hidden])
|
||||
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
|
||||
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
|
||||
W_fc2 = weight([fc_hidden, 10], stddev)
|
||||
b_fc2 = bias([10])
|
||||
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
|
||||
cross_entropy = tf.reduce_mean(
|
||||
-tf.reduce_sum(y * tf.log(y_conv), reduction_indices=[1]))
|
||||
correct_pred = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y, 1))
|
||||
return (tf.train.AdamOptimizer(lr).minimize(cross_entropy),
|
||||
tf.reduce_mean(tf.cast(correct_pred, tf.float32)), cross_entropy)
|
||||
|
||||
|
||||
# Define a remote function that takes a set of hyperparameters as well as the
|
||||
# data, consructs and trains a network, and returns the validation accuracy.
|
||||
@ray.remote
|
||||
def train_cnn_and_compute_accuracy(params,
|
||||
steps,
|
||||
train_images,
|
||||
train_labels,
|
||||
validation_images,
|
||||
validation_labels,
|
||||
weights=None):
|
||||
# Extract the hyperparameters from the params dictionary.
|
||||
learning_rate = params["learning_rate"]
|
||||
batch_size = params["batch_size"]
|
||||
keep = 1 - params["dropout"]
|
||||
stddev = params["stddev"]
|
||||
# Create the network and related variables.
|
||||
with tf.Graph().as_default():
|
||||
# Create the input placeholders for the network.
|
||||
x = tf.placeholder(tf.float32, shape=[None, 784])
|
||||
y = tf.placeholder(tf.float32, shape=[None, 10])
|
||||
keep_prob = tf.placeholder(tf.float32)
|
||||
# Create the network.
|
||||
train_step, accuracy, loss = cnn_setup(x, y, keep_prob, learning_rate,
|
||||
stddev)
|
||||
# Do the training and evaluation.
|
||||
with tf.Session() as sess:
|
||||
# Use the TensorFlowVariables utility. This is only necessary if we
|
||||
# want to set and get the weights.
|
||||
variables = ray.experimental.tf_utils.TensorFlowVariables(
|
||||
loss, sess)
|
||||
# Initialize the network weights.
|
||||
sess.run(tf.global_variables_initializer())
|
||||
# If some network weights were passed in, set those.
|
||||
if weights is not None:
|
||||
variables.set_weights(weights)
|
||||
# Do some steps of training.
|
||||
for i in range(1, steps + 1):
|
||||
# Fetch the next batch of data.
|
||||
image_batch = get_batch(train_images, i, batch_size)
|
||||
label_batch = get_batch(train_labels, i, batch_size)
|
||||
# Do one step of training.
|
||||
sess.run(
|
||||
train_step,
|
||||
feed_dict={
|
||||
x: image_batch,
|
||||
y: label_batch,
|
||||
keep_prob: keep
|
||||
})
|
||||
# Training is done, so compute the validation accuracy and the
|
||||
# current weights and return.
|
||||
totalacc = accuracy.eval(feed_dict={
|
||||
x: validation_images,
|
||||
y: validation_labels,
|
||||
keep_prob: 1.0
|
||||
})
|
||||
new_weights = variables.get_weights()
|
||||
return float(totalacc), new_weights
|
||||
Reference in New Issue
Block a user