<jupyter_start><jupyter_text>IPython notebook in Dr. H's class  Statistical distribution<jupyter_code>%pylab inline<jupyter_output>Populating the interactive namespace from numpy and matplotlib<jupyter_text>- Write a function that generates random coin flips, storing a value of 0 and +1 to correspond to heads and tails.- Then, write a loop to flip this X time (ie x = 1, 10, 100) and see what our average score (total number of heads - total number tails) is!<jupyter_code>import random

def fair_coin():
    return random.choice([0,1])<jupyter_output><empty_output><jupyter_text>Test it out<jupyter_code>def multi_trial(flips, flip_function):
    total = 0
    for i in range(FLIPS):
        total += flip_function()   
    return total
FLIPS = 10 #How many flips to do

score = multi_trial(FLIPS, fair_coin)
print 'Total score is: %s out of %s flips for "%s"' % (score, FLIPS, 'fair_coin')<jupyter_output>Total score is: 3 out of 10 flips for "fair_coin"<jupyter_text>What is a score that is out of the ordinary for 10 flips?  IE we expect on average, to get 0; however, we know that we won't always get 0.   We don't know the statistical distribution?  Let's test this for 1000 simulations of 10 flips.<jupyter_code>def simulation(trials=5, fcn=fair_coin, plot=True):
    ''' Run a function TRIALS times, plot the results in a histogram '''
    total = []
    for i in range(trials):
        total.append(multi_trial(FLIPS, fcn))

    if plot:
        plt.hist(total, bins=20, color='black')
        plt.title('%s trials of %s' % (trials, fcn.__name__))
        plt.xlabel('Score')
        plt.ylabel('Occurrences')
              
simulation(2000)<jupyter_output><empty_output><jupyter_text>**TRY THIS WITH MORE FLIPS PER TRIAL (IE CHANGE FLIPS)**  Notice how the space fills up! Is this the binomial distribution?<jupyter_code>from IPython.display import Image
Image(url='http://docs.scipy.org/doc/numpy/_images/math/d0e9bf22b11bd63cac4e02feb23f7c40e2c26943.png')<jupyter_output><empty_output><jupyter_text>We can use Numpy's [binomial distribution generator to check!](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html).<jupyter_code>help(np.random.binomial)
n, p = 10, .5 # number of trials, probability of each trial
s = np.random.binomial(n, p, size=1000) # result of flipping a coin 10 times, tested 1000 times.
plt.hist(s, bins=20);<jupyter_output><empty_output><jupyter_text>The variance of a binomial distribution follows the following formula:$V(X) = np(1-p)$Where n is the number of trials/flips.  The distribution is N, ie this was done thousands of times to get a real statistical distribution.Meaning the standard deviation is:$\sigma(x) = \sqrt{V(x)}$$\sigma(x) = \sqrt{np(1-p)}$For a fair coin:$\sigma(x) = \sqrt{n} \times 0.25$<jupyter_code>print 'std is %s' %(np.std(s))
print 'sqrt n times .25 is',sqrt(10.0 * 0.25)<jupyter_output>std is 1.52804417475
sqrt n times .25 is 1.58113883008<jupyter_text>**By the way, how fast this this?**<jupyter_code>%%timeit
s = np.random.binomial(n, p, size=1000) # result of flipping a coin 10 times, tested 1000 times.
%%timeit
simulation(2000, plot=False)<jupyter_output>10 loops, best of 3: 28.1 ms per loop<jupyter_text>**What, 100-1000 times faster?**  What about two coins We were pretty smart with our design of functions, so we can *ensemble* space, ie the number of possible outcomes.<jupyter_code>def two_flips():
    return fair_coin() + fair_coin()

simulation(trials=5000, fcn=two_flips, plot=True)<jupyter_output><empty_output><jupyter_text>IGNORE ME<jupyter_code>import os.path as op
from IPython.display import display, HTML

def load_style(s, figsize=None, loghide=False):
    """Load a CSS stylesheet in the notebook either by builtin styles, or
    from a file, or from a URL.
    Examples::
        %load_style 
        %load_style mystyle.css
        %load_style http://ipynbstyles.com/otherstyle.css
    """
    if s.startswith('http'):
        try:
            import requests
        except ImportError:
            raise ImportError('Failed to import python "requests" library;'
                              'please install to use load_style(url)')
        r =requests.get(s)
        style = r.text

    else:
        try:
            with open(s, 'r') as f:
                style = f.read()
        except IOError:
            raise IOError('Failed to load style as a url, file or builtin type.'
               ' Valid builtins are "%s"' % '","'.join(__all__.keys() ))

    out = '<style>\n{style}\n</style>'.format(style=style)
    
    if figsize:
        if figsize == True:
            figsize = 8, 5.5
        else:
            try:
                fx, fy = figsize
            except Exception:
                fx, fy = figsize, figsize
            
        fstring = "\ninput:pylab.rcParams['figure.figsize'] = %s, %s\n" \
            % (fx,fy)
        out += fstring

    display(HTML(out))
    
    if loghide:
        import warnings #supress non-skspec log msgs
        warnings.filterwarnings('ignore')      

#load_style('https://raw.githubusercontent.com/panditarevolution/ipythonNotebook_customs/master/monokai/custom.css')
load_style('https://raw.githubusercontent.com/hugadams/skspec/master/skspec/bundled/gwu.css')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11277482941622441, 'fraction_numerical': 0.027103866565579986, 'mean_word_length': 3.506404782237404, 'pattern_counts': {'":': 0, '<': 39, '<?xml version=': 0, '>': 39, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '536829', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 1876, 'n_tokens_neox': 1726, 'n_words': 513, 'path': 'examples/Notebooks/coinflips.ipynb', 'repo_name': 'hugadams/scikit-spectra', 'size': '5276'}