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)

  #############################################################################
  # 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!                                                           #
  #############################################################################
  num_classes = W.shape[1]
  num_train = X.shape[0]
  num_dim = X.shape[1]
  loss = 0.0
  for i in xrange(num_train):
    scores = X[i].dot(W)
    # correct_class_score = scores[y[i]]

    # stable trick
    unnormalized_log_possiblilty = scores - scores.max()
    unnormalized_possiblilty = np.exp(unnormalized_log_possiblilty)
    possibility = unnormalized_possiblilty / unnormalized_possiblilty.sum()
    loss += - np.log(possibility[y[i]])
    possibility[y[i]] -= 1
    dW += X[i].reshape([num_dim, 1]).dot(possibility.reshape([1, num_classes]))



  loss /= num_train
  dW /= num_train
  dW += reg * 2 * 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)

  #############################################################################
  # 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!                                                           #
  #############################################################################
  num_classes = W.shape[1]
  num_train = X.shape[0]
  loss = 0.0

  scores = X.dot(W)
  # correct_class_score = scores[y[i]]

  # stable trick
  unnormalized_log_possiblilty = scores - scores.max(1).reshape((num_train, 1))
  unnormalized_possiblilty = np.exp(unnormalized_log_possiblilty)
  possibility = unnormalized_possiblilty / unnormalized_possiblilty.sum(1).reshape((num_train, 1))
  loss += - np.log(y.choose(possibility.T)).sum()
  possibility[np.arange(num_train), y] -= 1  # strictly speaking it's no longer possibility after this step
  dscores = possibility
  dW += X.T.dot(dscores)

  loss /= num_train
  dW /= num_train
  dW += reg * 2 * W
  #############################################################################
  #                          END OF YOUR CODE                                 #
  #############################################################################

  return loss, dW

