import numpy as np
from random import shuffle
#from past.builtins import xrange

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)

  #############################################################################
  # TODO:                                                                     #
  # Compute the gradient of the loss function and store it dW.                #
  # Rather that first computing the loss and then computing the derivative,   #
  # it may be simpler to compute the derivative at the same time that the     #
  # loss is being computed. You may need to modify some of the                #
  # code above to compute the gradient.                                       #
  #############################################################################

  # Initialize the loss and gradient to zero.
  loss = 0.0
  dW = np.zeros_like(W)
  num_train = X.shape[0]
  num_classes = W.shape[1]
  num_dims = W.shape[0]

  for i in xrange(num_train):
    scores = X[i].dot(W)
    scores -=  np.max(scores) #To avoid numerical issues
    q = np.exp(scores) / np.sum(np.exp(scores))
    loss += -np.log(q[y[i]])
	# Compute gradient
    for d in xrange(num_dims):
      for k in xrange(num_classes):
        if k == y[i]:
          dW[d, k] += X.T[d, i] * (q[k]-1)
        else:
		  dW[d, k] += X.T[d, i] * q[k]
  
  
  loss /= num_train
 
  # Add regularization to the loss.
  loss += 0.5 * reg * np.sum(W * W)
 
  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 FUNCTION#
  scores = X.dot(W)
  scores -= np.max(scores, axis=1)[:, np.newaxis]
  exponential = np.exp(scores)
  probability = exponential / np.sum(exponential, axis=1, keepdims=True)
  loss = np.sum(-np.log(probability[np.arange(num_train), y]))
  loss += 0.5 * reg * np.sum(W * W)
  loss /= num_train	
  #GRADIENT#
  dscores = np.zeros_like(scores)
  dscores[np.arange(num_train), y] += -1
  dscores += probability
  dW = np.dot(X.T, dscores)
  dW += reg * W
  dW /= num_train
  #############################################################################
  #                          END OF YOUR CODE                                 #
  #############################################################################

  return loss, dW

