# CPSC 532P - Spring 2017 - http://cs.ubc.ca/~poole/cs532/2017
# This is not useful for much except answering this question for one predictor
# This requires Python 3 (get the latest version from http://python.org)

# Copyright David Poole, 2017
# This work is licensed under a Creative Commons
# Attribution-NonCommercial-ShareAlike 4.0 International License.
# See: http://creativecommons.org/licenses/by-nc-sa/4.0/deed.en

import random

num_iter = 1000
num_test = 100

def predictor(n0,n1):
    "Training proportion"
    return n1/(n0+n1)

def sum_sq(actual,prediction):   # each term in sum as a function of actual and predicted
    """Sum of squares error"""
    return (actual-prediction)**2
def sum_abs(actual,prediction):
    """Sum of absolute error"""
    return abs(actual-prediction)

for method in [sum_sq, sum_abs]:
    print(method.__doc__)
    print(predictor.__doc__, end='')
    for n in [1, 2, 3, 4, 5, 10, 20, 100, 1000]:
        error = 0.0
        for i in range(num_iter):
            p = random.random()
            n0, n1 = 0, 0
            for s in range(n):
                if random.random()<p :
                    n1 += 1
                else:
                    n0 += 1
            prediction = predictor(n0,n1)
            for tn in range(100):
                actual = 1 if random.random()<p else 0
                error += method(actual, prediction)
        print(' ||', error/num_iter,end='')
    print()
                
                
