Ejemplo n.º 1
0
def apply_validation_set(feature_combin, feature_mapping, weights):
    feature_combin.append(11)
    val_set, field_names = import_data("testing_data_split.csv",
                                       ";",
                                       True,
                                       columns=feature_combin)
    inputs = val_set[:, 0:val_set.shape[1] - 1]
    targets = val_set[:, val_set.shape[1] - 1:]
    pred_func = construct_feature_mapping_approx(feature_mapping, weights)
    pred_ys = pred_func(inputs)
    pred_targets = []
    for i in range(pred_ys.size):
        pred_targets.append(round(pred_ys[i], 0))
    targets = np.rot90(targets, 3)
    counter = 0
    for i in range(len(pred_targets)):
        if pred_targets[i] == targets[:, i]:
            counter += 1
    print("CORRECT: ", counter)
    print("WRONG: ", len(pred_targets) - counter)
def main(inputs, targets, scale, best_no_centres, test_fraction=0.20):
    # setting a seed to get the same pseudo-random results every time
    np.random.seed(30)

    print("\n")

    std_inputs = standardise(inputs)

    train_part, test_part = train_and_test_split(std_inputs.shape[0],
                                                 test_fraction)

    train_inputs, train_targets, test_inputs, test_targets = train_and_test_partition(
        std_inputs, targets, train_part, test_part)

    # specifying the centres of the rbf basis functions
    # choosing 10% of the data for the centres of the basis functions or the optimal proportion from earlier analyses
    centres = train_inputs[
        np.random.choice([False, True],
                         size=train_inputs.shape[0],
                         p=[1 - best_no_centres, best_no_centres]), :]
    print("centres shape = %r" % (centres.shape, ))

    # the width (analogous to standard deviation) of the basis functions
    # scale of the basis functions from analysis in external_data file
    # We consider the basis function widths to be fixed for simplicity
    print("scale = %r" % scale)

    # creating the feature mapping
    feature_mapping = construct_rbf_feature_mapping(centres, scale)

    # plotting the basis functions themselves for reference
    display_basis_functions(feature_mapping, train_inputs.shape[1])

    # alpha and beta define the shape of our curve when we start

    # beta is defining the noise precision of our data, as the reciprocal of the target variance
    # it is the spread from the highest point (top) of the curve
    # it corresponds to additive Gaussian noise of variance, which is beta to the power of -1
    beta = np.reciprocal(0.40365849982557295)
    # beta = np.reciprocal(np.var(train_targets))
    # beta = 100
    # higher beta is going to give us higher precision, so less overlap
    # as a side note, could also do beta = 1 / np.var(train_targets)

    # location of the highest point of the initial curve / prior distribution
    # because targets represent quality ranging from 0 to 10
    alpha = mode(targets)[0][0]
    # alpha = 100

    # now applying our feature mapping to the train inputs and constructing the design matrix
    design_matrix = feature_mapping(train_inputs)
    # the number of features (phis) is the width of this matrix
    # it is equal to the number of centres drawn from the train inputs
    # the shape[0] is the number of data points I use for training
    M = design_matrix.shape[1]

    # defining a prior mean and covariance matrix
    # they represent our prior belief over the distribution
    # our initial estimate of the range of probabilities
    m0 = np.zeros(M)

    for m in range(len(m0)):
        m0[m] = mode(targets)[0][0]  # setting to be the mode of targets
        # m0[m] = 0

    S0 = alpha * np.identity(M)

    # diagonal regularisation matrix A to punish over-fitting
    # A = alpha * np.identity(M)
    # E = 0.5 * m0.T * A * m0
    # Zp = regularisation constant
    # prior_m0 = np.exp(-E)/Zp

    # finding the posterior over weights
    # if we have enough data, the posteriors will be the same, no matter the initial parameters
    # because they will have been updated according to Bayes' rule
    mN, SN = calculate_weights_posterior(design_matrix, train_targets, beta,
                                         m0, S0)
    # print("mN = %r" % (mN,))

    # the posterior mean (also the MAP) gives the central prediction
    mean_approx = construct_feature_mapping_approx(feature_mapping, mN)

    # getting MAP and calculating root mean squared errors
    train_output = mean_approx(train_inputs)
    test_output = mean_approx(test_inputs)

    bayesian_mean_train_error = root_mean_squared_error(
        train_targets, train_output)
    bayesian_mean_test_error = root_mean_squared_error(test_targets,
                                                       test_output)
    print("Root mean squared errors:")
    print("Train error of posterior mean (applying Bayesian inference): %r" %
          bayesian_mean_train_error)
    print("Test error of posterior mean (applying Bayesian inference): %r" %
          bayesian_mean_test_error)

    # plotting one input variable on the x axis as an example
    fig, ax, lines = plot_function_and_data(std_inputs[:, 10], targets)

    # creating data to use for plotting
    xs = np.ndarray((101, train_inputs.shape[1]))

    for column in range(train_inputs.shape[1]):
        column_sample = np.linspace(-5, 5, 101)
        column_sample = column_sample.reshape((column_sample.shape[0], ))
        xs[:, column] = column_sample

    ys = mean_approx(xs)
    line, = ax.plot(xs[:, 10], ys, 'r-')
    lines.append(line)
    ax.set_ylim([0, 10])

    # now plotting a number of samples from the posterior
    for i in range(20):
        weights_sample = np.random.multivariate_normal(mN, SN)
        sample_approx = construct_feature_mapping_approx(
            feature_mapping, weights_sample)
        sample_ys = sample_approx(xs)
        line, = ax.plot(xs[:, 10], sample_ys, 'm', linewidth=0.5)
    lines.append(line)
    ax.legend(lines, ['data', 'mean approx', 'samples'])

    # now for the predictive distribution
    new_designmtx = feature_mapping(xs)
    ys, sigma2Ns = predictive_distribution(new_designmtx, beta, mN, SN)
    print("(sigma2Ns**0.5).shape = %r" % ((sigma2Ns**0.5).shape, ))
    print("np.sqrt(sigma2Ns).shape = %r" % (np.sqrt(sigma2Ns).shape, ))
    print("ys.shape = %r" % (ys.shape, ))

    ax.plot(xs[:, 10], ys, 'r', linewidth=3)
    lower = ys - np.sqrt(sigma2Ns)
    upper = ys + np.sqrt(sigma2Ns)
    print("lower.shape = %r" % (lower.shape, ))
    print("upper.shape = %r" % (upper.shape, ))
    ax.fill_between(xs[:, 10], lower, upper, alpha=0.2, color='r')
    ax.set_title('Posterior Mean, Samples, and Predictive Distribution')
    ax.set_xlabel('standardised alcohol content')
    ax.set_ylabel('p(t|x)')
    fig.tight_layout()
    fig.savefig("../plots/bayesian/bayesian_rbf.png", fmt="png")

    plt.show()

    # the predictive distribution
    test_design_matrix = feature_mapping(test_inputs)
    predictions, prediction_sigma2 = predictive_distribution(
        test_design_matrix, beta, mN, SN)
    sum_joint_log_probabilities = 0
    for n in range(len(predictions)):
        sum_joint_log_probabilities += math.log(predictions[n])

    sum_joint_log_probabilities *= -1
    # joint_log_probabilities = (np.array(test_targets).flatten() - np.array(predictions).flatten())
    # print(np.mean(joint_log_probabilities))
    print("Error as negative joint log probability: %r" %
          sum_joint_log_probabilities)
def main():
    """
    This function contains example code that demonstrates how to use the 
    functions defined in poly_fit_base for fitting polynomial curves to data.
    """

    # specify the centres of the rbf basis functions
    centres = np.linspace(0, 1, 9)
    # the width (analogous to standard deviation) of the basis functions
    scale = 0.1
    print("centres = %r" % (centres, ))
    print("scale = %r" % (scale, ))
    # create the feature mapping
    feature_mapping = construct_rbf_feature_mapping(centres, scale)
    # plot the basis functions themselves for reference
    display_basis_functions(feature_mapping)

    # sample number of data-points: inputs and targets
    N = 9
    # define the noise precision of our data
    beta = (1. / 0.1)**2
    inputs, targets = sample_data(N,
                                  arbitrary_function_1,
                                  noise=np.sqrt(1. / beta),
                                  seed=37)
    # now construct the design matrix for the inputs
    designmtx = feature_mapping(inputs)
    # the number of features is the widht of this matrix
    M = designmtx.shape[1]
    # define a prior mean and covaraince matrix
    m0 = np.zeros(M)
    alpha = 100
    S0 = alpha * np.identity(M)
    # find the posterior over weights
    mN, SN = calculate_weights_posterior(designmtx, targets, beta, m0, S0)
    # the posterior mean (also the MAP) gives the central prediction
    mean_approx = construct_feature_mapping_approx(feature_mapping, mN)
    fig, ax, lines = plot_function_data_and_approximation(
        mean_approx, inputs, targets, arbitrary_function_1)
    # now plot a number of samples from the posterior
    xs = np.linspace(0, 1, 101)
    print("mN = %r" % (mN, ))
    for i in range(20):
        weights_sample = np.random.multivariate_normal(mN, SN)
        sample_approx = construct_feature_mapping_approx(
            feature_mapping, weights_sample)
        sample_ys = sample_approx(xs)
        line, = ax.plot(xs, sample_ys, 'm', linewidth=0.5)
    lines.append(line)
    ax.legend(lines, ['true function', 'data', 'mean approx', 'samples'])
    ax.set_xticks([])
    ax.set_yticks([])
    fig.tight_layout()
    fig.savefig("regression_bayesian_rbf.pdf", fmt="pdf")

    # now for the predictive distribuiton
    new_inputs = np.linspace(0, 1, 51)
    new_designmtx = feature_mapping(new_inputs)
    ys, sigma2Ns = predictive_distribution(new_designmtx, beta, mN, SN)
    print("(sigma2Ns**0.5).shape = %r" % ((sigma2Ns**0.5).shape, ))
    print("np.sqrt(sigma2Ns).shape = %r" % (np.sqrt(sigma2Ns).shape, ))
    print("ys.shape = %r" % (ys.shape, ))
    fig, ax, lines = plot_function_and_data(inputs, targets,
                                            arbitrary_function_1)
    ax.plot(new_inputs, ys, 'r', linewidth=3)
    lower = ys - np.sqrt(sigma2Ns)
    upper = ys + np.sqrt(sigma2Ns)
    print("lower.shape = %r" % (lower.shape, ))
    print("upper.shape = %r" % (upper.shape, ))
    ax.fill_between(new_inputs, lower, upper, alpha=0.2, color='r')

    plt.show()
def main():
    """
    This function contains example code that demonstrates how to use the 
    functions defined in poly_fit_base for fitting polynomial curves to data.
    """

    # specify the centres of the rbf basis functions
    centres = np.linspace(0,1,7)
    # the width (analogous to standard deviation) of the basis functions
    scale = 0.15
    print("centres = %r" % (centres,))
    print("scale = %r" % (scale,))
    feature_mapping = construct_rbf_feature_mapping(centres,scale)  
    datamtx = np.linspace(0,1, 51)
    designmtx = feature_mapping(datamtx)
    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)
    for colid in range(designmtx.shape[1]):
      ax.plot(datamtx, designmtx[:,colid])
    ax.set_xlim([0,1])
    ax.set_xticks([0,1])
    ax.set_yticks([0,1])

    # choose number of data-points and sample a pair of vectors: the input
    # values and the corresponding target values
    N = 20
    inputs, targets = sample_data(N, arbitrary_function_1, seed=37)
    # define the feature mapping for the data
    feature_mapping = construct_rbf_feature_mapping(centres,scale)  
    # now construct the design matrix
    designmtx = feature_mapping(inputs)
    #
    # find the weights that fit the data in a least squares way
    weights = ml_weights(designmtx, targets)
    # use weights to create a function that takes inputs and returns predictions
    # in python, functions can be passed just like any other object
    # those who know MATLAB might call this a function handle
    rbf_approx = construct_feature_mapping_approx(feature_mapping, weights)
    fig, ax, lines = plot_function_data_and_approximation(
        rbf_approx, inputs, targets, arbitrary_function_1)
    ax.legend(lines, ['true function', 'data', 'linear approx'])
    ax.set_xticks([])
    ax.set_yticks([])
    fig.tight_layout()
    fig.savefig("regression_rbf.pdf", fmt="pdf")

    # for a single choice of regularisation strength we can plot the
    # approximating function
    reg_param = 10**-3
    reg_weights = regularised_ml_weights(
        designmtx, targets, reg_param)
    rbf_reg_approx = construct_feature_mapping_approx(feature_mapping, reg_weights)
    fig, ax, lines = plot_function_data_and_approximation(
        rbf_reg_approx, inputs, targets, arbitrary_function_1)
    ax.set_xticks([])
    ax.set_yticks([])
    fig.tight_layout()
    fig.savefig("regression_rbf_basis_functions_reg.pdf", fmt="pdf")

    # to find a good regularisation parameter, we can performa a parameter
    # search (a naive way to do this is to simply try a sequence of reasonable
    # values within a reasonable range.
    
    # sample some training and testing inputs
    train_inputs, train_targets = sample_data(N, arbitrary_function_1, seed=37)
    # we need to use a different seed for our test data, otherwise some of our
    # sampled points will be the same
    test_inputs, test_targets = sample_data(100, arbitrary_function_1, seed=82)
    # convert the raw inputs into feature vectors (construct design matrices)
    train_designmtx = feature_mapping(train_inputs)
    test_designmtx = feature_mapping(test_inputs)
    # now we're going to evaluate train and test error for a sequence of
    # potential regularisation strengths storing the results
    reg_params = np.logspace(-5,1)
    train_errors = []
    test_errors = []
    for reg_param in reg_params:
        # evaluate the test and train error for this regularisation parameter
        train_error, test_error = train_and_test(
            train_designmtx, train_targets, test_designmtx, test_targets,
            reg_param=reg_param)
        # collect the errors
        train_errors.append(train_error)
        test_errors.append(test_error)
    # plot the results
    fig, ax = plot_train_test_errors(
        "$\lambda$", reg_params, train_errors, test_errors)        
    ax.set_xscale('log')


    # we may also be interested in choosing the right number of centres, or
    # the right width/scale of the rbf functions.
    # Here we vary the width and evaluate the performance
    reg_param = 10**-3
    scales = np.logspace(-2,0)
    train_errors = []
    test_errors = []
    for scale in scales:
        # we must construct the feature mapping anew for each scale
        feature_mapping = construct_rbf_feature_mapping(centres,scale)  
        train_designmtx = feature_mapping(train_inputs)
        test_designmtx = feature_mapping(test_inputs)
        # evaluate the test and train error for this regularisation parameter
        train_error, test_error = train_and_test(
            train_designmtx, train_targets, test_designmtx, test_targets,
            reg_param=reg_param)
        # collect the errors
        train_errors.append(train_error)
        test_errors.append(test_error)
    # plot the results
    fig, ax = plot_train_test_errors(
        "scale", scales, train_errors, test_errors)        
    ax.set_xscale('log')

    # Here we vary the number of centres and evaluate the performance
    reg_param = 10**-3
    scale = 0.15
    n_centres_seq = np.arange(3,20)
    train_errors = []
    test_errors = []
    for n_centres in n_centres_seq:
        # we must construct the feature mapping anew for each number of centres
        centres = np.linspace(0,1,n_centres)
        feature_mapping = construct_rbf_feature_mapping(centres,scale)  
        train_designmtx = feature_mapping(train_inputs)
        test_designmtx = feature_mapping(test_inputs)
        # evaluate the test and train error for this regularisation parameter
        train_error, test_error = train_and_test(
            train_designmtx, train_targets, test_designmtx, test_targets,
            reg_param=reg_param)
        # collect the errors
        train_errors.append(train_error)
        test_errors.append(test_error)
    # plot the results
    fig, ax = plot_train_test_errors(
        "Num. Centres", n_centres_seq, train_errors, test_errors)        
    plt.show()
Ejemplo n.º 5
0
def parameter_search_rbf_cross(inputs, targets, folds,test_error_linear,test_inputs,test_targets,normalize=True):
    """
    This function will take as inputs the raw data and targets, the folds for cross validation and the test linear error for plotting
    """
    if(normalize):
        # normalise inputs (meaning radial basis functions are more helpful)
        for i in range(inputs.shape[1]):
            inputs[:,i]=(inputs[:,i]-np.mean(inputs[:,i]))/np.std(inputs[:,i])
            test_inputs[:,i]=(test_inputs[:,i]-np.mean(test_inputs[:,i]))/np.std(test_inputs[:,i])
    N = inputs.shape[0]

    # for the centres of the basis functions sample 10% of the data
    sample_fractions = np.array([0.05,0.1,0.15,0.2,0.25])
    scales = np.logspace(0,4,20 ) # of the basis functions
    reg_params = np.logspace(-16,-1, 20) # choices of regularisation strength.
    # create empty 3d arrays to store the train and test errors
    train_mean_errors = np.empty((sample_fractions.size,scales.size,reg_params.size))
    test_mean_errors = np.empty((sample_fractions.size,scales.size,reg_params.size))
    
    best_k=0
    best_i=0
    best_j=0
    test_error_temp=10**100
    
    #loop through the possible centres as a percentage (5%, 10%,15%, 20%, 25%)
    for k,sample_fraction in enumerate(sample_fractions):
        p = (1-sample_fraction,sample_fraction)
        centres = inputs[np.random.choice([False,True], size=N, p=p),:]
        # iterate over the scales
        for i,scale in enumerate(scales):
            # i is the index, scale is the corresponding scale
            # we must recreate the feature mapping each time for different scales
            feature_mapping = construct_rbf_feature_mapping(centres,scale)
            designmtx = feature_mapping(inputs)
            # iteratre over the regularisation parameters
            for j, reg_param in enumerate(reg_params):
                # j is the index, reg_param is the corresponding regularisation
                # parameter for train and test the data
                train_error, test_error,weights = cv_evaluation_linear_model(designmtx, targets, folds,reg_param=reg_param)
                
                #When we've found a lowest than stores test error value, we store it's indices
                if (np.mean(test_error)<test_error_temp):
                    test_error_temp=np.mean(test_error)
                    best_k=k
                    best_i=i
                    best_j=j
                    optimal_weights=weights
                    optimal_feature_mapping=feature_mapping
                    
                # store the train and test errors in our 3d matrix
                train_mean_errors[k,i,j] = np.mean(train_error)
                test_mean_errors[k,i,j] = np.mean(test_error)
    
    print ("The value with the lowest test error at the training stage is:",test_mean_errors[best_k][best_i][best_j])
    print("Best joint choice of parameters: sample fractions %.2g scale %.2g and lambda = %.2g" % (sample_fractions[best_k],scales[best_i],reg_params[best_j]))
    
    
    # now we can plot the error for different scales using the best regularization choice and centres percentage
    fig , ax = plot_train_test_errors("scale", scales, train_mean_errors[best_k,:,best_j], test_mean_errors[best_k,:,best_j])
    ax.set_xscale('log')
    fig.suptitle('RBF regression for the best reg. parameter & centres using cross-validation', fontsize=10)
    xlim = ax.get_xlim()#get the xlim to graph the linear regression
    ax.plot(xlim, test_error_linear*np.ones(2), 'g:') #graph the linear regression
    
    
    # ...and the error for  different regularisation choices given the best scale choice and centres percentage
    fig , ax = plot_train_test_errors("$\lambda$", reg_params, train_mean_errors[best_k,best_i,:], test_mean_errors[best_k,best_i,:])
    ax.set_xscale('log')
    fig.suptitle('RBF regression for the best scale parameter & centres using cross-validation', fontsize=10)
    xlim = ax.get_xlim()#get the xlim to graph the linear regression
    ax.plot(xlim, test_error_linear*np.ones(2), 'g:')
    # #ax.set_ylim([0,20])
    
    
    # ...and the error for  different centres given the best reg.parameter and the best scale choice
    fig , ax = plot_train_test_errors("sample fractions", sample_fractions, train_mean_errors[:,best_i,best_j], test_mean_errors[:,best_i,best_j])
    fig.suptitle('RBF regression for the best scale parameter & reg. parameter using cross-validation', fontsize=10)
    ax.set_xlim([0.05, 0.25])
    xlim = ax.get_xlim()#get the xlim to graph the linear regression
    ax.plot(xlim, test_error_linear*np.ones(2), 'g:')
    
    predictive_func=construct_feature_mapping_approx(optimal_feature_mapping, optimal_weights)
    
    final_error=root_mean_squared_error(test_targets,predictive_func(test_inputs))
    print("final test error for RBF model:",final_error)
def bayesian_regression_entry_point(data):
    """
    This function contains example code that demonstrates how to use the 
    functions defined in poly_fit_base for fitting polynomial curves to data.
    """

    data_targets = data[:, -1]
    data = data[:, 0:11]

    print(data)
    print(data_targets)
    for i in range(data.shape[1]):
        data[:, i] = (data[:, i] - np.mean(data[:, i])) / np.std(data[:, i])
    print("standard deviation is %s" % str(np.std(data, axis=0)))

    inputs = data[0:960, :]
    targets = data_targets[0:960]
    test_inputs = data[1300:1599, :]
    test_targets = data_targets[1300:1599]

    # specify the centres of the rbf basis functions
    N = inputs.shape[0]
    centres1 = inputs[np.random.choice([False, True], size=N, p=[0.9, 0.1]), :]
    # centres1 = data[10,:]
    # centres1 = np.linspace(4,20,10)
    print(centres1)

    # the width (analogous to standard deviation) of the basis functions
    scale = 47
    print("centres = %r" % (centres1, ))
    print("scale = %r" % (scale, ))
    # create the feature mapping
    feature_mapping = construct_rbf_feature_mapping(centres1, scale)
    # plot the basis functions themselves for reference

    # sample number of data-points: inputs and targets
    # define the noise precision of our data
    beta = (1 / 0.01)**2
    # now construct the design matrix for the inputs
    designmtx = feature_mapping(inputs)
    test_designmtx = feature_mapping(test_inputs)
    print(designmtx.shape)
    # the number of features is the width of this matrix
    M = designmtx.shape[1]
    # define a prior mean and covaraince matrix
    # m0 = np.random.randn(M)
    m0 = np.zeros(M)
    print("m0 equals %r" % (m0))
    alpha = 50
    S0 = alpha * np.identity(M)
    # find the posterior over weights
    mN, SN = calculate_weights_posterior(designmtx, targets, beta, m0, S0)
    # for i in range(500):
    #     mN, SN = calculate_weights_posterior(designmtx, targets, beta, mN, SN)

    train_error, test_error = train_and_test(designmtx, targets,
                                             test_designmtx, test_targets, mN)
    print(train_error, test_error)

    # cross-validation
    # train_error, test_error = cv_evaluation_linear_model(designmtx, targets, folds, mN)
    # print(train_error, test_error, np.mean(train_error), np.mean(test_error))

    # the posterior mean (also the MAP) gives the central prediction
    mean_approx = construct_feature_mapping_approx(feature_mapping, mN)
    fig, ax, lines = plot_function_data_and_approximation(
        mean_approx, test_inputs, test_targets)
    ax.legend(lines, ['Prediction', 'True value'])
    ax.set_xticks([])
    ax.set_ylabel("Quality")
    fig.suptitle('Prediction vlaue against True value', fontsize=10)
    fig.savefig("regression_bayesian_rbf.pdf", fmt="pdf")

    # search the optimum alpha for baysian model regression
    train_inputs = data[0:960, :]
    train_targets = data_targets[0:960]
    test_inputs = data[960:1300, :]
    test_targets = data_targets[960:1300]
    # folds = create_cv_folds(train_inputs.shape[0], num_folds)
    alphas = np.logspace(1, 3)

    # convert the raw inputs into feature vectors (construct design matrices)
    # train_errors = np.empty(alphas.size)
    # test_errors = np.empty(alphas.size)
    train_errors = []
    test_errors = []
    for a, alpha in enumerate(alphas):
        # we must construct the feature mapping anew for each scale
        feature_mapping = construct_rbf_feature_mapping(centres1, scale)
        train_designmtx = feature_mapping(train_inputs)
        test_designmtx = feature_mapping(test_inputs)

        beta = (1 / 0.01)**2
        M = train_designmtx.shape[1]
        # define a prior mean and covaraince matrix
        m0 = np.zeros(M)

        S0 = alpha * np.identity(M)
        # find the posterior over weights
        mN, SN = calculate_weights_posterior(train_designmtx, train_targets,
                                             beta, m0, S0)

        # evaluate the test and train error for this regularisation parameter
        train_error, test_error = train_and_test(train_designmtx,
                                                 train_targets, test_designmtx,
                                                 test_targets, mN)
        train_errors.append(train_error)
        test_errors.append(test_error)
        # train_error, test_error = cv_evaluation_linear_model(train_designmtx, train_targets, folds, mN)
        # train_errors[a] = np.mean(train_error)
        # test_errors[a] = np.mean(test_error)
    # plot the results
    min_error = np.min(test_errors)
    min_error_index = np.argmin(test_errors)
    fig, ax = plot_train_test_errors("alpha", alphas, train_errors,
                                     test_errors)
    fig.suptitle('Alpha vs Error in Bayesian', fontsize=10)
    ax.plot(alphas[min_error_index], min_error, "ro")
    # ax.text(scales[min_error_index],min_error,(str(scales[min_error_index]),str(min_error)))
    ax.annotate((str(alphas[min_error_index]), str(min_error)),
                xy=(alphas[min_error_index], min_error),
                xytext=(alphas[min_error_index] + 0.01, min_error + 0.01),
                arrowprops=dict(facecolor='green', shrink=0.1))
    ax.set_xscale('log')
    fig.savefig("alpha.pdf", fmt="pdf")

    # search the optimum beta for baysian model regression
    train_inputs = data[0:960, :]
    train_targets = data_targets[0:960]
    test_inputs = data[960:1300, :]
    test_targets = data_targets[960:1300]
    # folds = create_cv_folds(train_inputs.shape[0], num_folds)
    betas = (1. / np.logspace(-3, 1))**2

    # convert the raw inputs into feature vectors (construct design matrices)
    # train_errors = np.empty(betas.size)
    # test_errors = np.empty(betas.size)
    train_errors = []
    test_errors = []
    for b, beta in enumerate(betas):
        # we must construct the feature mapping anew for each scale
        feature_mapping = construct_rbf_feature_mapping(centres1, scale)
        train_designmtx = feature_mapping(train_inputs)
        test_designmtx = feature_mapping(test_inputs)

        M = train_designmtx.shape[1]
        # define a prior mean and covaraince matrix
        m0 = np.zeros(M)
        alpha = 50
        S0 = alpha * np.identity(M)
        # find the posterior over weights
        mN, SN = calculate_weights_posterior(train_designmtx, train_targets,
                                             beta, m0, S0)

        # evaluate the test and train error for this regularisation parameter
        train_error, test_error = train_and_test(train_designmtx,
                                                 train_targets, test_designmtx,
                                                 test_targets, mN)
        train_errors.append(train_error)
        test_errors.append(test_error)

        # train_error, test_error = cv_evaluation_linear_model(train_designmtx, train_targets, folds, mN)
        # train_errors[b] = np.mean(train_error)
        # test_errors[b] = np.mean(test_error)
    # plot the results
    min_error = np.min(test_errors)
    min_error_index = np.argmin(test_errors)
    fig, ax = plot_train_test_errors("beta", betas, train_errors, test_errors)
    fig.suptitle('Beta vs Error in Bayesian', fontsize=10)
    ax.plot(betas[min_error_index], min_error, "ro")
    # ax.text(scales[min_error_index],min_error,(str(scales[min_error_index]),str(min_error)))
    ax.annotate((str(betas[min_error_index]), str(min_error)),
                xy=(betas[min_error_index], min_error),
                xytext=(betas[min_error_index] + 0.05, min_error + 0.05),
                arrowprops=dict(facecolor='green', shrink=0.1))
    ax.set_xscale('log')
    fig.savefig("beta.pdf", fmt="pdf")

    # search the optimum scale for baysian model regression
    scales = np.logspace(0.5, 3)
    train_inputs = data[0:960, :]
    train_targets = data_targets[0:960]
    test_inputs = data[960:1300, :]
    test_targets = data_targets[960:1300]
    # folds = create_cv_folds(train_inputs.shape[0], num_folds)

    # convert the raw inputs into feature vectors (construct design matrices)
    # train_errors = np.empty(scales.size)
    # test_errors = np.empty(scales.size)
    train_errors = []
    test_errors = []
    for j, scale in enumerate(scales):
        # we must construct the feature mapping anew for each scale
        feature_mapping = construct_rbf_feature_mapping(centres1, scale)
        train_designmtx = feature_mapping(train_inputs)
        test_designmtx = feature_mapping(test_inputs)

        beta = (1. / 0.01)**2
        M = train_designmtx.shape[1]
        # define a prior mean and covaraince matrix
        m0 = np.zeros(M)
        alpha = 50
        S0 = alpha * np.identity(M)
        # find the posterior over weights
        mN, SN = calculate_weights_posterior(train_designmtx, train_targets,
                                             beta, m0, S0)

        # evaluate the test and train error for this regularisation parameter
        train_error, test_error = train_and_test(train_designmtx,
                                                 train_targets, test_designmtx,
                                                 test_targets, mN)
        # train_error, test_error = cv_evaluation_linear_model(train_designmtx, train_targets, folds, mN)
        # train_errors[j] = np.mean(train_error)
        # test_errors[j] = np.mean(test_error)

        train_errors.append(train_error)
        test_errors.append(test_error)
    # plot the results
    min_error = np.min(test_errors)
    min_error_index = np.argmin(test_errors)
    fig, ax = plot_train_test_errors("scale", scales, train_errors,
                                     test_errors)
    fig.suptitle('Scale vs Error in Bayesian', fontsize=10)
    ax.plot(scales[min_error_index], min_error, "ro")
    # ax.text(scales[min_error_index],min_error,(str(scales[min_error_index]),str(min_error)))
    ax.annotate((str(scales[min_error_index]), str(min_error)),
                xy=(scales[min_error_index], min_error),
                xytext=(scales[min_error_index] + 0.2, min_error + 0.2),
                arrowprops=dict(facecolor='green', shrink=0.1))
    ax.set_xscale('log')
    fig.savefig("scale.pdf", fmt="pdf")

    # Here we vary the number of centres and evaluate the performance
    scale = 60
    train_inputs = data[0:960, :]
    train_targets = data_targets[0:960]
    test_inputs = data[960:1300, :]
    test_targets = data_targets[960:1300]
    # folds = create_cv_folds(train_inputs.shape[0], num_folds)
    cent_parts = np.linspace(0.05, 0.8, 16)
    # train_errors = np.empty(cent_parts.size)
    # test_errors = np.empty(cent_parts.size)
    train_errors = []
    test_errors = []
    N = train_inputs.shape[0]

    for n, cent_part in enumerate(cent_parts):
        # we must construct the feature mapping anew for each number of centres
        centres1 = train_inputs[np.random.choice(
            [False, True], size=N, p=[1 - cent_part, cent_part]), :]

        feature_mapping = construct_rbf_feature_mapping(centres1, scale)
        train_designmtx = feature_mapping(train_inputs)
        test_designmtx = feature_mapping(test_inputs)
        # evaluate the test and train error for this regularisation parameter

        M = train_designmtx.shape[1]
        # define a prior mean and covaraince matrix
        m0 = np.zeros(M)
        beta = (1. / 0.01)**2
        alpha = 50
        S0 = alpha * np.identity(M)
        # find the posterior over weights
        mN, SN = calculate_weights_posterior(train_designmtx, train_targets,
                                             beta, m0, S0)

        train_error, test_error = train_and_test(train_designmtx,
                                                 train_targets, test_designmtx,
                                                 test_targets, mN)
        train_errors.append(train_error)
        test_errors.append(test_error)

        # train_error, test_error = cv_evaluation_linear_model(train_designmtx, train_targets, folds, mN)
        # train_errors[n] = np.mean(train_error)
        # test_errors[n] = np.mean(test_error)
    # plot the results
    min_error = np.min(test_errors)
    min_error_index = np.argmin(test_errors)
    fig, ax = plot_train_test_errors("Num. Centres", cent_parts, train_errors,
                                     test_errors)
    fig.suptitle('Num. Centres vs Error in Bayesian', fontsize=10)
    ax.plot(cent_parts[min_error_index], min_error, "ro")
    ax.text(cent_parts[min_error_index], min_error,
            (str(cent_parts[min_error_index]), str(min_error)))
    fig.savefig("Num. centres.pdf", fmt="pdf")

    plt.show()