import numpy as np
from random import shuffle

def softmax_loss_naive(W, X, y, reg):
  """
  Softmax loss function, naive implementation (with loops)

  Inputs have dimension D, there are C classes, and we operate on minibatches
  of N examples.

  Inputs:
  - W: A numpy array of shape (D, C) containing weights.
  - X: A numpy array of shape (N, D) containing a minibatch of data.
  - y: A numpy array of shape (N,) containing training labels; y[i] = c means
    that X[i] has label c, where 0 <= c < C.
  - reg: (float) regularization strength

  Returns a tuple of:
  - loss as single float
  - gradient with respect to weights W; an array of same shape as W
  """
  # Initialize the loss and gradient to zero.
  loss = 0.0
  dW = np.zeros_like(W)
  num_train = X.shape[0]
  #############################################################################
  # TODO: Compute the softmax loss and its gradient using explicit loops.     #
  # Store the loss in loss and the gradient in dW. If you are not careful     #
  # here, it is easy to run into numeric instability. Don't forget the        #
  # regularization!                                                           #
  #############################################################################
  # Loss
  d = X.dot(W) # NumInstances x Classes
  d -= np.max(d, axis=1).reshape(-1, 1) # For numeric stability
  d_exp = np.exp(d) # Raise all of them to Exp
  d_exp_sums = np.sum(d_exp, axis=1).reshape(-1, 1) # Calculate the denominators
  d_exp_reg = d_exp / d_exp_sums # Normalize
  Li = -np.log(d_exp_reg[np.arange(len(d_exp_reg)), y])
  loss = np.sum(Li) / num_train # Data loss
  loss += 0.5 * reg * np.sum(W * W) # Add the regularization loss
    
  # Gradient
  # https://eli.thegreenplace.net/2016/the-softmax-function-and-its-derivative/
  # for derivation
  probs = d_exp_reg
  probs[np.arange(num_train),y] -= 1
  dW = X.T.dot(probs)
  dW /= num_train
  dW += reg * W
  #############################################################################
  #                          END OF YOUR CODE                                 #
  #############################################################################

  return loss, dW


def softmax_loss_vectorized(W, X, y, reg):
  """
  Softmax loss function, vectorized version.

  Inputs and outputs are the same as softmax_loss_naive.
  """
  # Initialize the loss and gradient to zero.
  loss = 0.0
  dW = np.zeros_like(W)
  num_train = X.shape[0]
  #############################################################################
  # TODO: Compute the softmax loss and its gradient using no explicit loops.  #
  # Store the loss in loss and the gradient in dW. If you are not careful     #
  # here, it is easy to run into numeric instability. Don't forget the        #
  # regularization!                                                           #
  #############################################################################
  # Loss
  d = X.dot(W) # NumInstances x Classes
  d -= np.max(d, axis=1).reshape(-1, 1) # For numeric stability
  d_exp = np.exp(d) # Raise all of them to Exp
  d_exp_sums = np.sum(d_exp, axis=1).reshape(-1, 1) # Calculate the denominators
  d_exp_reg = d_exp / d_exp_sums # Normalize
  Li = -np.log(d_exp_reg[np.arange(len(d_exp_reg)), y])
  loss = np.sum(Li) / num_train # Data loss
  loss += 0.5 * reg * np.sum(W * W) # Add the regularization loss
    
  # Gradient
  probs = d_exp_reg
  probs[np.arange(num_train),y] -= 1
  dW = X.T.dot(probs)
  dW /= num_train
  dW += reg * W
  #############################################################################
  #                          END OF YOUR CODE                                 #
  #############################################################################

  return loss, dW

