import numpy as np
import itertools
from matplotlib import pyplot as plt
from sklearn.model_selection import KFold

def calculate_accuracy(predicted_classes, actual_classes):
  return sum(predicted_classes == actual_classes)/len(actual_classes)


def kfold_predictions(model, features, targets, k):
    kf = KFold(n_splits=k, shuffle=True)

    # declare an array for predicted redshifts from each iteration
    all_predictions = np.zeros_like(targets)

    for train_indices, test_indices in kf.split(features):
        # split the data into training and testing
        train_f, test_f = features[train_indices], features[test_indices]
        train_t, test_t = targets[train_indices], targets[test_indices]
        # fit the model for the current set
        model.fit(train_f, train_t)
        # predict using the model
        predictions = model.predict(test_f)    
        # put the predicted values in the all_predictions array defined above
        all_predictions[test_indices] = predictions

  # return the predictions
    return all_predictions  

def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    cm: array, shape=[n_classes, n_classes]
        confusion matrix generated by sklearn.metrics.confusion_matrix
    classes: list
        class label of the database
    normalize: False/True
        if normalize=True, each element of the matrix is normalized by
        the total number of that class
    cmap: 

    --------------------------------------------------------------------
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, "{}".format(cm[i, j]),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True Class')
    plt.xlabel('Predicted Class')