baotrung217

logistic_regression_tensorflow

May 20th, 2018
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.91 KB | None | 0 0
  1. # Implements a logistic regression with mini-batch gradient descent using tensorflow
  2. # testing with the sklearn moons dataset
  3.  
  4. import tensorflow as tf
  5. import numpy as np
  6. from datetime import datetime
  7. from sklearn.datasets import make_moons
  8.  
  9.  
  10. def get_tb_dir(prefix=None) -> str:
  11.     """ Returns a string using the current time that serves as the directory
  12.    that will be used as the folder to save data for TensorBoard. It uses
  13.    the current time data to prevent merging of data in TensorBoard.
  14.    """
  15.     now = datetime.utcnow().strftime("%Y%m%d%H%M%S")
  16.     return "{}/run-{}".format(prefix, now)
  17.  
  18.  
  19. def log_reg_graph(X, y, n: int, learning_rate: float=0.01):
  20.     """ Creates a tensorflow graph that can be used for a logistic regression.
  21.    This can be reused multiple times.
  22.    :param m: the number of elements in the X matrix (an m x n matrix)
  23.    :param learning_rate: the learning rate to use for gradient descent
  24.    """
  25.     with tf.name_scope("log_reg") as scope:
  26.         with tf.name_scope("variables") as scope:
  27.             w = tf.Variable(tf.random_uniform(
  28.                 [n + 1, 1], -1.0, 1.0), name="weights")
  29.  
  30.         with tf.name_scope("pred") as scope:
  31.             logits = tf.matmul(X, w, name="logits")
  32.             y_pred = tf.sigmoid(logits, name="sigmoid")
  33.  
  34.         with tf.name_scope("loss") as scope:
  35.             log_loss = tf.losses.log_loss(y, y_pred)
  36.             log_loss_summary = tf.summary.scalar("log_loss_sum", log_loss)
  37.             optimizer = tf.train.GradientDescentOptimizer(
  38.                 learning_rate=learning_rate)
  39.             training_op = optimizer.minimize(log_loss)
  40.  
  41.         with tf.name_scope("init") as scope:
  42.             init = tf.global_variables_initializer()
  43.  
  44.         with tf.name_scope("save") as scope:
  45.             saver = tf.train.Saver()
  46.  
  47.     return w, logits, y_pred, log_loss, log_loss_summary, optimizer, \
  48.         training_op, init, saver
  49.  
  50.  
  51. def get_batch(X, y, batch_size: int):
  52.     """ Given a matrix X, returns a mini-batch of "batch_size"
  53.    given which batch we're on
  54.    """
  55.     indices = np.random.randint(0, len(X), size=batch_size)
  56.     X_batch = X[indices].astype(dtype=np.float32)
  57.     # y.reshape(-1, 1)[indices]
  58.     y_batch = y.reshape(-1, 1)[indices].astype(dtype=np.float32)
  59.     return X_batch, y_batch
  60.  
  61.  
  62. def log_reg_with_ckpt(X_data, y_data, X_test, y_test, n, n_epochs, learning_rate, batch_size):
  63.     """ Executes a logistic regression on a given X with a given y. This will
  64.    log data and save checkpoints as well, just in case execution is
  65.    interrupted.
  66.    """
  67.     # Variables needed for the graph
  68.     # directory prefix for tensorboard and checkpoints
  69.     dir_pref = get_tb_dir("./log_reg")
  70.     n_batches = int(np.ceil(n / batch_size))
  71.     X = tf.placeholder(tf.float32, shape=(None, n + 1), name="X")
  72.     y = tf.placeholder(tf.float32, shape=(None, 1), name="y")
  73.  
  74.     # Create computation graph
  75.     w, logits, y_pred, log_loss, log_loss_summary, optimizer, \
  76.         training_op, init, saver = log_reg_graph(X, y, n, learning_rate)
  77.  
  78.     file_writer = tf.summary.FileWriter(dir_pref, tf.get_default_graph())
  79.  
  80.     with tf.Session() as sess:
  81.         sess.run(init)
  82.  
  83.         for epoch in range(n_epochs):
  84.             for batch_index in range(n_batches):
  85.                 X_batch, y_batch = get_batch(X_data, y_data, batch_size)
  86.                 # , y: y_batch})
  87.                 sess.run(training_op, feed_dict={X: X_batch, y: y_batch})
  88.  
  89.             if epoch % 100 == 0:
  90.                 print("Epoch:", epoch, " | log loss:", log_loss.eval(
  91.                     feed_dict={X: X_test, y: y_test}))
  92.                 save_path = saver.save(
  93.                     sess, "{}/logistic_model.ckpt".format(dir_pref))
  94.  
  95.             if epoch % 10 == 0:
  96.                 summary_str = log_loss_summary.eval(
  97.                     feed_dict={X: X_test, y: y_test})
  98.                 file_writer.add_summary(summary_str, epoch)
  99.  
  100.         save_path = saver.save(
  101.             sess, "{}/logistic_model_final.ckpt".format(dir_pref))
  102.         file_writer.close()
  103.  
  104.  
  105. def get_moons_data(m):
  106.     """Retrieves the moons dataset and returns an X, and a y.
  107.    """
  108.     X_moons, y_moons = make_moons(m, noise=0.1, random_state=42)
  109.     return X_moons, y_moons
  110.  
  111.  
  112. def main():
  113.     # retrieve the data
  114.     m = 1000
  115.     X_data, y_data = get_moons_data(m)
  116.     X_data_bias = np.c_[np.ones((m, 1)), X_data]
  117.     m, n = X_data.shape  # need the shape for tensorflow placeholders
  118.  
  119.     # split the test/train data
  120.     test_ratio = 0.2
  121.     test_size = int(m * test_ratio)
  122.     X_train = X_data_bias[:-test_size]
  123.     X_test = X_data_bias[-test_size:]
  124.     y_train = y_data[:-test_size]
  125.     y_test = y_data[-test_size:]
  126.  
  127.     tf.reset_default_graph()
  128.  
  129.     # run the regression
  130.     log_reg_with_ckpt(X_train, y_train, X_test, y_test.reshape(-1, 1),
  131.                       n, n_epochs=2000, learning_rate=0.1, batch_size=100)
  132.  
  133.  
  134. if __name__ == "__main__":
  135.     main()
Advertisement
Add Comment
Please, Sign In to add comment