# Notebook from mgaringoDev/mgaringoDev.github.io
Path: python/Convert DB into MD.ipynb

import numpy as np
import pandas as pd_____no_output_____db = pd.read_csv("..\_data\projectsDB.csv")_____no_output_____db.head()_____no_output_____# for index, row in db.iterrows():
#     title = row["Title"].replace(" ","-")
#     fileName = "{}-{}.md".format(row["Date"],title)
#     fileLocation = "..\_posts\projects\{}".format(row["ImageFolderLocation"])
#     fileSave = fileLocation + "\\" + fileName
#     print("{}".format(fileSave))
# #     print("---")
# #     print("layout: post")
# #     print("title: {}".format(row["Title"]))
# #     print("date: {}".format(row['Date']))
# #     print("tags: {} {}".format(row['Category'],row['Sub-Category']))
# #     print("---")

# #     print("\n")
# #     print("![{}]({})".format(row["ProjectID"],row["ImageLocation"]))

# #     print("\n")
# #     print("**Project Lifespan\\:**{}".format(row["Year"]))

# #     print("\n")
# #     print("{}".format(row["Description"]))_____no_output_____

# Creating Blog Posts_____no_output_____

for index, row in db.iterrows():

    title = row["Title"].replace(" ","-")
    fileName = "{}-{}.md".format(row["Date"],title)
    fileLocation = "..\_posts\projects\{}".format(row["ImageFolderLocation"])
    fileSave = fileLocation + "\\" + fileName

    print("Now Creating File {}".format(fileName))

    f = open(fileSave,"w")

    f.write("---\n")
    f.write("layout: post\n")
    f.write("title: {}\n".format(row["Title"]))
    f.write("date: {}\n".format(row['Date']))
    f.write("tags: {} {}\n".format(row['Category'],row['Sub-Category']))
    f.write("---\n")

    f.write("**Project Lifespan\\:** {}  \n".format(row["Year"]))
    f.write("
\n")

    # This was the working copy but it wasn't centering properly
    # f.write("![{}]({})\n".format(row["ProjectID"],row["ImageLocation"]))

    f.write("\n")
    f.write("{}".format(row["Description"]))

    f.close()
    print("Finsied")Now Creating File 2015-04-05-Neuroscience-to-Education.md
Finsied
Now Creating File 2016-09-01-Headache-Sciences-Inc.md
Finsied
Now Creating File 2014-01-05-Educational-Brain-Atlas-Using-Source-Localization-Technique.md
Finsied
Now Creating File 2015-11-23-Responsive-Brain-Holograms.md
Finsied
Now Creating File 2016-05-29-WebGL-Viewer-for-EEG-Source-Localization.md
Finsied
Now Creating File 2016-10-13-Medical-Holography.md
Finsied
Now Creating File 2014-03-24-Developed-Standardization-of-Poster-and-Movie-Generation-for-Portrait-of-Your-Mind.md
Finsied
Now Creating File 2014-07-12-Developed-Automated-Extraction-of-Information-of-Forms-for-Travel-Vaccine-Clinic.md
Finsied
Now Creating File 2013-09-06-A-Collaborative-Pilot-Study-with-Stanford-University-for-Autonomous-Patient-Medical-Adherence-Monitoring-for-Asthma-.md
Finsied
Now Creating File 2013-10-25-EEG-Brain-State-Analysis-Listening-to-Music-During-Meditation.md
Finsied
Now Creating File 2012-10-20-Listen-To-Your-Mind.md
Finsied
Now Creating File 2014-06-16-A-Pilot-Study-of-Epilepsy-Seizure-Structure-Using-Tensor-Analysis-and-Source-Localization-with-Sick-Kids-Hospital.md
Finsied
Now Creating File 2015-10-18-An-EEG-Based-Diagnosis-for-Alzheimers.md
Finsied
Now Creating File 2013-10-12-An-EEG-Based-Predictive-Model-for-Fibromyalgia.md
Finsied
Now Creating File 2015-08-21-The-Atlas-of-the-Generators-of-Sleep.md
Finsied
Now Creating File 2012-06-06-Helped-Develop-a-Non-Parametric-Spatiotemporal-Clustering-of-Time-Varying-Current-Density-Vectors-in-the-Cerebral-Cortex.md
Finsied
Now Creating File 2015-05-25-Pilot-Study-of-EEG-Motor-Movement-and-Imagery-Analysis-Using-Source-Localization.md
Finsied
Now Creating File 2015-08-14-A-Collaborative-Pilot-Study-with-Algoma-University-for-Phoneme-Detection-Using-EEG-Auditory-Evoked-Potentials.md
Finsied
Now Creating File 2016-09-15-A-Collaborative-Pilot-Study-with-Algoma-University-for-Word-Detection-Using-EEG-Auditory-Evoked-Potentials.md
Finsied
Now Creating File 2015-10-11-A-collaboration-with-Sheridan-University-To-Create-A-Portable-19-Channel-EEG-Cap-Including-Amplifier.md
Finsied
Now Creating File 2014-05-11-EEG-Artifact-Rejection-and-Noise-Reduction-Algorithms.md
Finsied

# Creating Tags_____no_output_____

catList = []
for index, row in db.iterrows():
    itemCategoryString = "{} {}".format(row['Category'],row['Sub-Category'])
    for word in itemCategoryString.split(" "):
        catList.append(word)   _____no_output_____uniqueTags = np.unique(catList)_____no_output_____for tag in uniqueTags:
    fileName = "{}.md".format(tag)
    fileLocation = "..\pages\\tags\{}".format(fileName)
    fileSave = fileLocation

    print("Now Creating File {}".format(fileName))

    f = open(fileSave,"w")

    f.write("---\n")
    f.write("layout: tag\n")
    f.write("title: {}\n".format(tag))
    f.write("category: {}\n".format("tagPages"))
    f.write("---\n")

    f.close()
    print("Finsied")Now Creating File Alzheimers.md
Finsied
Now Creating File Auscultation.md
Finsied
Now Creating File BrainComputerInterface.md
Finsied
Now Creating File Business.md
Finsied
Now Creating File EEG.md
Finsied
Now Creating File Epilepsy.md
Finsied
Now Creating File Fibromyalgia.md
Finsied
Now Creating File MachineLearning.md
Finsied
Now Creating File Meditation.md
Finsied
Now Creating File NeuralNetwork.md
Finsied
Now Creating File OptimizationofWorkflow.md
Finsied
Now Creating File Pre-Processing.md
Finsied
Now Creating File Research.md
Finsied
Now Creating File Seizure.md
Finsied
Now Creating File SoftwareDevelopment.md
Finsied
Now Creating File SourceLocalization.md
Finsied
Now Creating File StartUps.md
Finsied
Now Creating File UnsupervisedLearning.md
Finsied
Now Creating File Visualization.md
Finsied


# Notebook from UWInSpace/InSpace
Path: notebooks/Tool_Flow_JK.ipynb

# Tool Flow
Per the user input

Functions in this notebook and what they wrap:
`predict_log2fc()`
1. `usr_seq()`
    a. `get_seq()`

2. `get_feat()`
    a. `get_prot_mass()`
    b. `get_biopy_feat()`
    c. `count_aa_types()`

3. `scale_input_feat()`

4. `bagging_regr()` - the modeling function that outputs the predicted log2fc
5. `vizualization_thing_here()`

`multi_pred_log2fc()`_____no_output_____### Imports_____no_output_____

import Bio
from Bio import Entrez
from Bio.SeqUtils.ProtParam import ProteinAnalysis
import math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Import Scikit-Learn library for the regression model
import sklearn
from sklearn import preprocessing #sklearn for normalization function
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
#for Bagging regressor
from sklearn.ensemble import BaggingRegressor
from sklearn.tree import DecisionTreeRegressor_____no_output_____

## The `usr_seq` Function_____no_output_____

def usr_seq(user_input, email):
    """If user input is an integer (EID and not a sequence that would be a string), get the sequence
    """
    t = type(user_input)
    if t is int:
        user_sequence = get_seq(email, user_input)
    else:
        user_sequence = user_input

    return user_sequence_____no_output_____def test_usr_seq():
    # Case 1: input is EID
    email = 'jaking11@uw.edu'
    usr_in = 15599626
    result = usr_seq(usr_in, email)
    assert result is str, 'the usr_seq function does not work'
    # Case 2: input is sequence
    usr_in = 'juliaisthecoolest'
    result = usr_seq(usr_in, email)
    assert result == usr_in, 'the usr_seq function does not work'
    return_____no_output_____test_usr_seq()_____no_output_____

## The `get_seq` function_____no_output_____

# definition of function:
def get_seq(email, prot_accession_num):
    Entrez.email = email

    gis = [prot_accession_num]
    request = Entrez.epost("protein",id=",".join(map(str,gis)))
    result = Entrez.read(request)
    webEnv = result["WebEnv"]
    queryKey = result["QueryKey"]
    handle = Entrez.efetch(db="protein",retmode="xml", webenv=webEnv, query_key=queryKey)

    for r in Entrez.parse(handle):
        try:
            gi=int([x for x in r['GBSeq_other-seqids'] if "gi" in x][0].split("|")[1])
        except ValueError:
            gi=None
        #print(r['GBSeq_sequence'])
        seq = r['GBSeq_sequence']
    return seq_____no_output_____def test_get_seq():
    seq = get_seq("karanjia@uw.edu", 728886557)
    expect = 'mlrsmltasttlnqlqqqidtissnlsnsnttgykakdtnfselvrqqfdqvdekneevakarktppglrlgvgammssrlvsdqgsiqktdrdldiaftspyqylqvnvngnrqytrdgalyvtpsaananqlqlvtgngypvldengntvnidssmknitinkngtltasdgnavqrfnlgvvqvnnpqelksegnnlfsidnaaafeelnganrqnigmqqgslemsnvdiseqmtdlitsqrsyqlnsrtitmgdqmlglinsvr'
    assert seq == expect, 'the get_seq function is not working'_____no_output_____

## Functions to support `get_feat` below_____no_output_____### `get_prot_mass`_____no_output_____

def get_prot_mass(AASeq):

    '''Tabulate approximate total mass of input amino acid string based on the sum of
    the average masses for every amino acid in the string.'''

    # Create dict with amino acid sybols as keys and associated average masses as values
    # Average masses taken from http://proteomicsresource.washington.edu/protocols06/masses.php
    molecular_mass_dict = {
    'A':71.0779,
    'R':156.18568,
    'G':57.05132,
    'S':87.0773,
    'P':97.11518,
    'V':99.13106,
    'T':101.10388,
    'C':103.1429,
    'L':113.15764,
    'I':113.15764,
    'N':114.10264,
    'D':115.0874,
    'Q':128.12922,
    'K':128.17228,
    'E':129.11398,
    'M':131.19606,
    'H':137.13928,
    'F':147.17386,
    'U':150.3079,
    'Y':163.17326,
    'W':186.2099,
    'O':237.29816
    }

    # Calculate approx mass for amino acid sequence
    mass_list = []

    # Capitalize all letters in amino acid string prior to taking mass
    AASeq = AASeq.upper()

    # Raise error if amino acid sequence contains characters not in the dict
    acceptable_amino_acids_list = list(molecular_mass_dict.keys())

    for char in AASeq:
        if char not in acceptable_amino_acids_list:
            if char == ' ':
                continue
            else:
                raise ValueError('AASeq contains unacceptable characters')

    for amino_acid, mw in molecular_mass_dict.items():
        aa_weight = AASeq.count(amino_acid)*mw
        mass_list.append(aa_weight)
    total_mass = sum(mass_list)

    return total_mass_____no_output_____

### `get_biopy_feat`_____no_output_____

def get_biopy_feat(sequence):
    """
    Taken-in dataframe with a column specified as 'SEQUENCE' and uses Biopython to
    generate additional features from each protein sequence to help better train a machine
    learning model to predict log2FC
    """
    ProtA = ProteinAnalysis(sequence)
    molwt_biopy = ProtA.molecular_weight()
    aromaticity = ProtA.aromaticity()
    isoelectric_pt = ProtA.isoelectric_point()

    return molwt_biopy, aromaticity, isoelectric_pt_____no_output_____

### `count_aa_types`_____no_output_____

def count_aa_types(sequence):
    '''here, sequence is an element in a list, not a list itself
    Function takes the sequence, counts how many times amino acids occur per each of 4
    groups and returns values as percentages of the total amino acides in the sequence'''
    l = len(sequence)

    ninja = {
        'nonpolar': ['G', 'g', 'A', 'a', 'V', 'v', 'C', 'c', 'P', 'p', 'L', 'l', 'I', 'i', 'M', 'm', 'W', 'w', 'F', 'f'],
        'positive': ['K', 'k', 'R', 'r', 'H', 'h'],
        'polar': ['S', 's', 'T', 't', 'Y', 'y', 'N', 'n', 'Q', 'q'],
        'negative': ['D', 'd', 'E', 'e']
    }

    # Initiate lists for counts
    nonpolar_l = []
    positive_l = []
    polar_l = []
    negative_l = []

    for i in range(l):
        aa = sequence[i]
        if aa in ninja['nonpolar']:
            nonpolar_l.append(1)
        elif aa in ninja['positive']:
            positive_l.append(1)
        elif aa in ninja['polar']:
            polar_l.append(1)
        else:
            negative_l.append(1)

    # Sum the lists to return
    nonpolar_c = sum(nonpolar_l)
    positive_c = sum(positive_l)
    polar_c = sum(polar_l)
    negative_c = sum(negative_l)

    # Percentage calculation to return
    nonpolar = nonpolar_c / l *100
    positive = positive_c / l *100
    polar = polar_c / l *100
    negative = negative_c / l *100

    return nonpolar, positive, polar, negative_____no_output_____

## The `get_feat` function_____no_output_____

def get_feat(user_sequence):
    """
    This function takes the sequence that the user is querying and returns a dataframe appended
    with all of the features used in the predictive model
    """

    mass = get_prot_mass(user_sequence)

    molwt_biopy, aromaticity, isoelectric_pt = get_biopy_feat(user_sequence)

    nonpolar, positive, polar, negative = count_aa_types(user_sequence)

    # Make the features into a Pandas DataFrame
    column_names = ['AA_NP', 'AA_POS', 'AA_POL', 'AA_NEG', 'MW', 'AROM', 'ISO_E']
    feat_list = [nonpolar, positive, polar, negative, mass, aromaticity, isoelectric_pt]
    feat_df = pd.DataFrame([feat_list], columns=column_names)

    return feat_df_____no_output_____user_sequence = 'mlrsmltasttlnqlqqqidtissnlsnsnttgykakdtnfselvrqqfdqvdekneevakarktppglrlgvgammssrlvsdqgsiqktdrdldiaftspyqylqvnvngnrqytrdgalyvtpsaananqlqlvtgngypvldengntvnidssmknitinkngtltasdgnavqrfnlgvvqvnnpqelksegnnlfsidnaaafeelnganrqnigmqqgslemsnvdiseqmtdlitsqrsyqlnsrtitmgdqmlglinsvr'
df = get_feat(user_sequence)
df_____no_output_____def test_get_feat():
    user_sequence = 'mlrsmltasttlnqlqqqidtissnlsnsnttgykakdtnfselvrqqfdqvdekneevakarktppglrlgvgammssrlvsdqgsiqktdrdldiaftspyqylqvnvngnrqytrdgalyvtpsaananqlqlvtgngypvldengntvnidssmknitinkngtltasdgnavqrfnlgvvqvnnpqelksegnnlfsidnaaafeelnganrqnigmqqgslemsnvdiseqmtdlitsqrsyqlnsrtitmgdqmlglinsvr'
    result_df = get_feat(user_sequence)
    result_test = result_df['MW'][0]
    expect = 29484.36112
    assert math.isclose(result_test, expect)_____no_output_____test_get_feat()_____no_output_____

## The `scale_input_feat` function_____no_output_____

def scale_input_feat(X):
    '''
    The function takes in X (our input features), and rescale based on min-max normalization
    it returns the normalized X
    '''
    #returns a numpy array for X (needed to use the min_max_scaler)
    X_arr = X.values

    X_col_names = list(X.columns.values.tolist()) #get column names to then put back into X_norm

    #min-max normalization (rescaling) of input features
    min_max_scaler = preprocessing.MinMaxScaler()
    X_scaled = min_max_scaler.fit_transform(X_arr)
    X_norm= pd.DataFrame(X_scaled)

    #put back the original column names
    X_norm.columns = X_col_names

    return X_norm_____no_output_____

## The `bagging_regr` function_____no_output_____

def bagging_regr(X_user):
    '''
    the function takes in the master csv and user input
    csv_file should be inputted as a string = 'compiled_features_complete.csv'
    test ratio, random state and n_estimator are set (from previous ML optimization)
    returning the predicted output based on user input
    '''

    # Open and load dataset
    bacterial_csv = pd.read_csv('UWInSpace_ModelData.csv')
    df = pd.DataFrame(data=bacterial_csv)

    #assign input (X) /output (y) features
    X= df[['AA_NP','AA_POS', 'AA_POL','AA_NEG', 'MW', 'AROM', 'ISO_E']]
    y= df['LOG2FC']

    #Scale input features
    X_arr = X.values #returns a numpy array for X (needed to use the min_max_scaler)

    X_col_names = list(X.columns.values.tolist()) #get column names to then put back into X_norm

    #min-max normalization (rescaling) of input features
    min_max_scaler = preprocessing.MinMaxScaler()
    X_scaled = min_max_scaler.fit_transform(X_arr)
    X_norm= pd.DataFrame(X_scaled)

    #put back the original column names
    X_norm.columns = X_col_names

    #set Bagging regressor parameters, from ML training:
    test_ratio = 0.30
    seed_random = 42
    n_estim= 20

    X_train, X_test, y_train, y_test = train_test_split(X_norm, y, test_size=test_ratio, random_state=seed_random, shuffle=True)
    #Model is Bagging Regressor, base estimator is Decision Tree regressor
    model = BaggingRegressor(base_estimator=DecisionTreeRegressor(),n_estimators=n_estim, random_state=seed_random)
    model.fit(X_train, y_train)
    #y_testpredict = model.predict(X_test)

    user_predict = model.predict(X_user)

    return user_predict_____no_output_____

# Overall tool function:_____no_output_____

def predict_log2fc(user_input, email):
    """
    This function takes the user input of either a protein accesion number or
    an amino acid sequence and predicts how much the sequence will change after
    being in space (near-zero gravity and increased radiation exposure)
    """

    # Get user sequence
    user_sequence = usr_seq(user_input, email)

    # Get features
    user_features_df = get_feat(user_sequence)

    # Scale features
    scaled_features_df = scale_input_feat(user_features_df)

    # Predict log2fc
    prediction = bagging_regr(scaled_features_df)
    prediction = prediction[0]
    prediction = round(prediction, 4)

    user_features_df['LOG2FC'] = [prediction]

    print('The predicted log2fc is ', prediction)

    return prediction, user_features_df_____no_output_____

## Do multiple predictions_____no_output_____

def multi_pred_log2fc(user_inputs, email):
    """Input the proteins of interest as a list.  This function will iterate through
    and return a list of predicted log2fc's.
    """

    input_length = len(user_input)

    # Initiate results list
    result_log2fc = []

    for i in range(input_length):
        result = predict_log2fc(user_input[i], email)
        result_log2fc.append(result)

    return result_log2fc_____no_output_____

## Trying it out...*gulp*_____no_output_____

user_input = 15600267
email = 'jaking11@uw.edu'
prediction, user_features_df = predict_log2fc(user_input, email)_____no_output_____user_features_df_____no_output_____user_features_df.to_csv('practice_viz_AK.csv')_____no_output_____


# Notebook from ML-Bioinfo-CEITEC/mirna_binding
Path: notebook/generate_encori_train_test_datasets_lock.ipynb

_____no_output_____# Machine Setup

The cell runs commands to install the required Python package `pybedtools` as

well as to download the human reference genome used by ENCORI database._____no_output_____

# install pybedtools
!apt-get install bedtools
!pip install pybedtools

# download encori ago2 dataset
!wget https://github.com/ML-Bioinfo-CEITEC/mirna_binding/raw/master/data/encori/encori_ago2.tsv.gz

# download reference genome, annotation, targetscan families
!wget ftp://ftp.ebi.ac.uk/pub/databases/gencode/Gencode_human/release_34/GRCh37_mapping/GRCh37.primary_assembly.genome.fa.gz
!wget ftp://ftp.ebi.ac.uk/pub/databases/gencode/Gencode_human/release_34/GRCh37_mapping/gencode.v34lift37.basic.annotation.gtf.gz
!wget http://www.targetscan.org/vert_72/vert_72_data_download/miR_Family_Info.txt.zip

# decompress files
!gunzip GRCh37.primary_assembly.genome.fa.gz
!gunzip gencode.v34lift37.basic.annotation.gtf.gz
!unzip miR_Family_Info.txt.zip
!gunzip encori_ago2.tsv.gz
Reading package lists... Done
Building dependency tree
Reading state information... Done
bedtools is already the newest version (2.26.0+dfsg-5).
The following package was automatically installed and is no longer required:
  libnvidia-common-440
Use 'apt autoremove' to remove it.
0 upgraded, 0 newly installed, 0 to remove and 59 not upgraded.
Requirement already satisfied: pybedtools in /usr/local/lib/python3.6/dist-packages (0.8.1)
Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from pybedtools) (1.12.0)
Requirement already satisfied: pysam in /usr/local/lib/python3.6/dist-packages (from pybedtools) (0.16.0.1)
--2020-06-20 11:02:11--  https://github.com/ML-Bioinfo-CEITEC/mirna_binding/raw/master/data/encori/encori_ago2.tsv.gz
Resolving github.com (github.com)... 140.82.114.3
Connecting to github.com (github.com)|140.82.114.3|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://raw.githubusercontent.com/ML-Bioinfo-CEITEC/mirna_binding/master/data/encori/encori_ago2.tsv.gz [following]
--2020-06-20 11:02:11--  https://raw.githubusercontent.com/ML-Bioinfo-CEITEC/mirna_binding/master/data/encori/encori_ago2.tsv.gz
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.0.133, 151.101.64.133, 151.101.128.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|151.101.0.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 10792332 (10M) [application/octet-stream]
Saving to: ‘encori_ago2.tsv.gz’

encori_ago2.tsv.gz  100%[===================>]  10.29M  20.5MB/s    in 0.5s

2020-06-20 11:02:12 (20.5 MB/s) - ‘encori_ago2.tsv.gz’ saved [10792332/10792332]

--2020-06-20 11:02:20--  ftp://ftp.ebi.ac.uk/pub/databases/gencode/Gencode_human/release_34/GRCh37_mapping/GRCh37.primary_assembly.genome.fa.gz
           => ‘GRCh37.primary_assembly.genome.fa.gz’
Resolving ftp.ebi.ac.uk (ftp.ebi.ac.uk)... 193.62.197.74
Connecting to ftp.ebi.ac.uk (ftp.ebi.ac.uk)|193.62.197.74|:21... connected.
Logging in as anonymous ... Logged in!
==> SYST ... done.    ==> PWD ... done.
==> TYPE I ... done.  ==> CWD (1) /pub/databases/gencode/Gencode_human/release_34/GRCh37_mapping ... done.
==> SIZE GRCh37.primary_assembly.genome.fa.gz ... 869924494
==> PASV ... done.    ==> RETR GRCh37.primary_assembly.genome.fa.gz ... done.
Length: 869924494 (830M) (unauthoritative)

GRCh37.primary_asse 100%[===================>] 829.62M  4.16MB/s    in 2m 53s

2020-06-20 11:05:14 (4.80 MB/s) - ‘GRCh37.primary_assembly.genome.fa.gz’ saved [869924494]

--2020-06-20 11:05:17--  ftp://ftp.ebi.ac.uk/pub/databases/gencode/Gencode_human/release_34/GRCh37_mapping/gencode.v34lift37.basic.annotation.gtf.gz
           => ‘gencode.v34lift37.basic.annotation.gtf.gz’
Resolving ftp.ebi.ac.uk (ftp.ebi.ac.uk)... 193.62.193.138
Connecting to ftp.ebi.ac.uk (ftp.ebi.ac.uk)|193.62.193.138|:21... connected.
Logging in as anonymous ... Logged in!
==> SYST ... done.    ==> PWD ... done.
==> TYPE I ... done.  ==> CWD (1) /pub/databases/gencode/Gencode_human/release_34/GRCh37_mapping ... done.
==> SIZE gencode.v34lift37.basic.annotation.gtf.gz ... 35269604
==> PASV ... done.    ==> RETR gencode.v34lift37.basic.annotation.gtf.gz ... done.
Length: 35269604 (34M) (unauthoritative)

gencode.v34lift37.b 100%[===================>]  33.63M  20.2MB/s    in 1.7s

2020-06-20 11:05:20 (20.2 MB/s) - ‘gencode.v34lift37.basic.annotation.gtf.gz’ saved [35269604]

--2020-06-20 11:05:21--  http://www.targetscan.org/vert_72/vert_72_data_download/miR_Family_Info.txt.zip
Resolving www.targetscan.org (www.targetscan.org)... 18.4.1.128
Connecting to www.targetscan.org (www.targetscan.org)|18.4.1.128|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 162636 (159K) [application/zip]
Saving to: ‘miR_Family_Info.txt.zip.1’

miR_Family_Info.txt 100%[===================>] 158.82K   586KB/s    in 0.3s

2020-06-20 11:05:21 (586 KB/s) - ‘miR_Family_Info.txt.zip.1’ saved [162636/162636]

gzip: GRCh37.primary_assembly.genome.fa already exists; do you wish to overwrite (y or n)? n
	not overwritten
gzip: gencode.v34lift37.basic.annotation.gtf already exists; do you wish to overwrite (y or n)? n
	not overwritten
Archive:  miR_Family_Info.txt.zip
replace miR_Family_Info.txt? [y]es, [n]o, [A]ll, [N]one, [r]ename: n
gzip: encori_ago2.tsv already exists; do you wish to overwrite (y or n)? n
	not overwritten

# General Python Modules_____no_output_____

import pandas as pd
import numpy as np
import pybedtools_____no_output_____

# Paramenters
This section allows the user to define train paramenters:
- NEG_RATIO: starting ratio for samples of the negative class (int., def. 1);
- RANDOM_STATE: set random state for reproducibility (int., def. 1789);
- WINDOW_SIZE: size of windows overlapping real binding site
- TIMES: number of windows expanding from real binding site

_____no_output_____

NEG_RATIO = 20
RANDOM_STATE = 1789
WINDOW_SIZE = 50
TIMES = 10
np.random.seed(RANDOM_STATE)
_____no_output_____

## negative class generator

The function generates the negative class by creating a connection between each

binding site and all mirna (expect the real one). If argument mirna_dict is

provided as dictionary of mirna sequences, this dictionary will be used to

create the negative class. Otherwise, all unique mirna sequences of the input

df will be used to generate samples for the negative class._____no_output_____

def negative_class_generator(df, mirna_dict=None,
                            neg_ratio=None, random_state=None):
    """
    create miRNA negative by shuffling the input dataset

    parameters:
    df=original pandas dataframe
    mirna_dict=optional miRNA dataframe
    neg_ratio=generate N number of miRNA negatives
    random_state=set seed for reproducibility

    outputs:
    miRNA negative set
    """
    if not mirna_dict:
        # generate mirna db of unique sequences
        mirnadb = pd.DataFrame(
            df.mirna_binding_sequence.unique(), columns=['mirnaid']
        )
    else:
        mirnadb = pd.DataFrame(mirna_dict)
        mirnadb.columns = ['mirnaid']
    # add mirna db to each row of df
    connections = mirnadb.assign(key=1).merge(
          df.assign(key=1), on='key'
          ).drop(['key', 'label'],axis=1)
    # find index of positive connection
    positive_samples_mask = (connections.mirnaid ==
                             connections.mirna_binding_sequence)
    # drop positive connection to create negative samples
    negative_df = connections[~positive_samples_mask].copy().drop(
      ['mirna_binding_sequence'], axis=1
      ).reset_index(drop=True)
    # rename cols
    negative_df.columns = ['mirna_binding_sequence', 'binding_sequence']
    # add negative labels
    negative_df['label'] = 'negative'
    if neg_ratio == None:
        return negative_df
    else:
        neg_samples = int(df.shape[0] * neg_ratio)
        return negative_df.sample(
            n = neg_samples,
            random_state=random_state)_____no_output_____

# ENCORI Preprocessing_____no_output_____## Load Encori Dataset and Create Test Set
The Encori Dataset was obtained by downloading the whole dataset through the Encori API at [URL](http://www.sysu.edu.cn/403.html).

The cell loads the original ENCORI dataset, which is filtered for only binding regions mapping on chromosome 1 and obtained by immunoprecipitation of AGO2.

Encori original database should contain 2055403 samples, and after filtering the new dataset should contain 460120 samples.

expected output:

Encori original AGO2 samples are: (460120, 23)

_____no_output_____

#load encori
encori_original = pd.read_csv('encori_ago2.tsv', sep='\t', comment='#')
# filter encori
# encori_original_chr1 = encori_original[(
#     encori_original.chromosome == 'chr1') &
#     (encori_original.RBP == 'AGO2')].reset_index(drop=True)
# assign unique id to each sample
encori_original['name'] = encori_original.index.to_list()

print('Encori original AGO2 samples are:',
      encori_original.shape)
# print('Encori original AGO2 samples mapping to chrom1 are:',
#       encori_original.shape)Encori original AGO2 samples are: (460120, 23)

## Filter ENCORI

This cell removes ENCORI samples not mapping on UTR.

1. load annotation;
2. filter `encori_original` for UTR regions only.

expected output:

samples mapping on UTR are: (425370, 22)_____no_output_____

# 1. load annotation and retrive chrom1 only features.

gtf_annotation = pd.read_csv('gencode.v34lift37.basic.annotation.gtf',
                             sep='\t', comment='#',
                             names=['chromosome', 'source', 'feature', 'start',
                                    'end', 'score', 'strand', 'frame',
                                    'attribute'])
gtf_annotation_UTR_only = gtf_annotation[
                                      (gtf_annotation.feature == 'UTR')
                                      ].copy()

# filter encori_original with pybedtools.
encori_original[['chromosome',
       'narrowStart', 'narrowEnd', 'name']].to_csv(
           'a.bed', sep='\t',
           header=False, index=False)

gtf_annotation_UTR_only[['chromosome',
       'start', 'end']].to_csv('b.bed', sep='\t', header=False, index=False)

a = pybedtools.BedTool('a.bed')
b = pybedtools.BedTool('b.bed')

overlaps = pybedtools.BedTool.intersect(a, b, wa=True, u=True).to_dataframe()

ago2_utr = pd.merge(
    encori_original, overlaps, on='name').drop(
    ['chrom', 'start', 'end', 'name'], axis=1)

print('samples mapping on UTR are:', ago2_utr.shape)samples mapping on UTR are: (425370, 22)

## Filter for unique binding site

This cell removes binding sites that are targeted by multiple miRNAs.

expected output:

ambiguous binding sites are: 222480

certain binding sites are: 202890

certain Encori database samples are: (202890, 22)
_____no_output_____

ambiguous_bs = list()
unique = 0
for name, group in ago2_utr.groupby([
            'chromosome', 'narrowStart', 'narrowEnd']):
    if group.shape[0] != 1: # more than one miRNA targeted this region
        ambiguous_bs += group.index.to_list()
    else:
        unique += 1
print('ambiguous binding sites are:', len(ambiguous_bs))
print('certain binding sites are:', unique)

ago2_utr_certain = ago2_utr.drop(
    ambiguous_bs).reset_index(drop=True)
print('certain Encori database samples are:', ago2_utr_certain.shape)ambiguous binding sites are: 222480
certain binding sites are: 202890
certain Encori database samples are: (202890, 22)

## Assign unique name to each sample

_____no_output_____

ago2_utr_certain['name'] = [ mirna + "_" + str(index)
    for mirna, index in zip(ago2_utr_certain['miRNAid'].to_list(),
                            ago2_utr_certain.index.to_list())]_____no_output_____

## Generate binding site coordinates and sequences for miRNA Neg. test set

The cell expands the original narrowStart and narrowEnd binding site coordinates

to a random window of 50nt.

expected output:

average Encori database binding site length is: 50.0

min. Encori database binding site length is: 50

max Encori database binding site length is: 50

Encori with positive binding sites sequence shape is: (202890, 28)_____no_output_____

def midpoint(row):
    """
    function extract the genomic coordiantes of binding site's midpoint.

    paramenters:
    row=dataframe row

    returns:
    midpoint (int.)
    """
    start = row.narrowStart
    end = row.narrowEnd
    mid = int(round((end - start) / 2, 0))
    midpoint = start + mid
    return midpoint_____no_output_____ago2_utr_certain['midpoint'] = ago2_utr_certain.apply(
    midpoint, axis=1)
ago2_utr_certain['random_int'] = np.random.randint(
    15, 30, ago2_utr_certain.shape[0])
ago2_utr_certain['random_start'] = (
    ago2_utr_certain['narrowStart'] -
    ago2_utr_certain['random_int'])
ago2_utr_certain['random_end'] = (
    ago2_utr_certain['random_start'] + WINDOW_SIZE)

print('average Encori database binding site length is:', (
    ago2_utr_certain['random_end'] -
    ago2_utr_certain['random_start']).mean() )
print('min. Encori database binding site length is:', (
    ago2_utr_certain['random_end'] -
    ago2_utr_certain['random_start']).min() )
print('max Encori database binding site length is:', (
    ago2_utr_certain['random_end'] -
    ago2_utr_certain['random_start']).max() )average Encori database binding site length is: 50.0
min. Encori database binding site length is: 50
max Encori database binding site length is: 50
positive_bindings_col = [
                 'chromosome', 'random_start',
                 'random_end', 'name',
                 'pancancerNum', 'strand']
positive_bindings_bed = 'positive_bindings.bed'

ago2_utr_certain[positive_bindings_col].to_csv(
    positive_bindings_bed, sep='\t', index=False, header=False)

bedfile = pybedtools.BedTool(positive_bindings_bed)
seq_filename = bedfile.sequence(
    fi='GRCh37.primary_assembly.genome.fa',
    s=True, tab=True, name=True).seqfn

seq_df = pd.read_csv(
    seq_filename, sep='\t', header=None, names=['name', 'pos_sequence'])

ago2_utr_certain = pd.concat(
    [ago2_utr_certain, seq_df['pos_sequence']], axis=1)

print('Encori with positive binding sites sequence shape is:',
      ago2_utr_certain.shape)Encori with positive binding sites sequence shape is: (202890, 28)
ago2_utr_certain[ago2_utr_certain.chromosome == 'chr1'].shape_____no_output_____

## Plug-in miRNA family sequence_____no_output_____

targetscan_family_df = pd.read_csv('miR_Family_Info.txt', sep='\t')
targetscan_family_df.columns = [ 'miRFamily', 'Seed+m8', 'SpeciesID',
               'MiRBase ID', 'MatureSequence',
               'Family Conservation?', 'miRNAid']

# assign miRNA family to Encori df
ago2_with_family = pd.merge(
    ago2_utr_certain,
    targetscan_family_df, on=['miRNAid'])

print(ago2_with_family[ago2_with_family.chromosome == 'chr1'].shape)(21385, 34)
updated_families = list()
for family, group in ago2_with_family.groupby('miRFamily'):
    filter_seq = sorted(
        group.MatureSequence.unique().tolist(),
        key=lambda x: len(x), reverse=True)[0]
    if len(filter_seq) < 20: # fill with N
        filter_seq = filter_seq + ('N' * 20)
    # trim seq at len 20
    filter_seq = filter_seq[ : 20].replace('U', 'T')
    x = group.copy()
    x['familyseqRepresentative'] = filter_seq
    updated_families.append(x)

encori_ago2_precessed = pd.concat(updated_families)

print(encori_ago2_precessed[encori_ago2_precessed.chromosome == 'chr1'].shape)(21385, 35)

# Generate Train set

The cell generates the positive sample class dataset for the training of the

model. The negative class is generated on the fly during the training process.

This cell extracts all samples expect those mapping on chromosome 1, which are

kept for the test set.

expected output:

train set size is: (179148, 35)_____no_output_____

encori_train_positive_samples = encori_ago2_precessed[
                encori_ago2_precessed.chromosome != 'chr1'
                ].reset_index(drop=True)

print('train set size is:', encori_train_positive_samples.shape)

encori_train_positive_samples.head(10)train set size is: (179148, 35)

## Generate coordinates for Scan Test Set

> Indented block

The cell extends the binding site coordinates of 10 windows of 50nt from the 5'

and 3' ends.

expected outputs:

encori ago2 on chromosome 1 shape is: (21385, 37)

Encori with scan binding sites sequence shape is: (21385, 38)_____no_output_____

encori_chrom1 = encori_ago2_precessed[
                encori_ago2_precessed.chromosome == 'chr1'
                ].reset_index(drop=True)

encori_chrom1['scan_start'] = (
    encori_chrom1['random_start'] - (WINDOW_SIZE * TIMES))
encori_chrom1['scan_end'] = (
    encori_chrom1['random_end'] + (WINDOW_SIZE * TIMES))

print('encori ago2 on chromosome 1 shape is:', encori_chrom1.shape)encori ago2 on chromosome 1 shape is: (21385, 37)
scan_col = [
            'chromosome', 'scan_start', 'scan_end',
            'name', 'pancancerNum', 'strand']

scan_name = 'scan.bed'
encori_chrom1[scan_col].to_csv(
    scan_name, sep='\t', index=False, header=False)

bedfile = pybedtools.BedTool(scan_name)
seq_filename = bedfile.sequence(
    fi='GRCh37.primary_assembly.genome.fa',
    s=True, tab=True, name=True).seqfn

seq_df = pd.read_csv(
    seq_filename, sep='\t', header=None, names=['name', 'scan_sequence'])

encori_chrom1_scan = pd.concat(
    [encori_chrom1, seq_df['scan_sequence']], axis=1)

print('Encori with scan binding sites sequence shape is:',
      encori_chrom1_scan.shape)
Encori with scan binding sites sequence shape is: (21385, 38)

## Create Scan and miRNA Neg Test sets

The function `break_seq` breaks the extracted scanning region into windows of

50nt size. It returns the miRNA sequence, real binding site sequence, and

the 20 segmented surrounding windows.

expected output:

positive df samples are: (21385, 3)

scan negative df samples are: (427700, 3)

scan test df samples are: (449085, 3)

miRNA neg samples are: (427700, 3)

mirna neg test df samples are: (449085, 3)_____no_output_____

def break_seq(row):
    """
    breaks scan sequence into windows of 50nt length.

    parameters:

    row=dataframe row

    returns:
    mirnaseq, pos_sequence, segments
    """
    segments = list()
    mirnaseq = row.familyseqRepresentative
    region = row.scan_sequence
    pos_sequence = row.pos_sequence
    for window, index in enumerate(range(0, len(region), 50)):
        if window == 10: # this is the real binding window
            continue
        segment = region[index : index + 50]
        segments.append( (segment) )
    return (mirnaseq, pos_sequence, segments)

breaks = encori_chrom1_scan.apply(break_seq, axis=1)_____no_output_____positive_samples_list = list()
scan_neg_list = list()

# create positive sample list and negative segments for scan test set
for sample in breaks:
    mirnaseq, pos_sequence, segments = sample
    positive_samples_list.append([mirnaseq, pos_sequence, 'positive'])
    for neg_segment in segments:
        scan_neg_list.append([mirnaseq, neg_segment, 'negative'])

# generate dataframe of positive bindings
positive_samples_df = pd.DataFrame(
    positive_samples_list,
    columns = ['mirna_binding_sequence', 'binding_sequence', 'label'])
# generate dataframe of negative bindings
scan_neg_df = pd.DataFrame(
    scan_neg_list,
    columns = ['mirna_binding_sequence', 'binding_sequence', 'label'])
# generate dataframe of miRNA negative
mirna_neg_set = negative_class_generator(
        positive_samples_df, neg_ratio=NEG_RATIO,
        random_state=RANDOM_STATE)
# concatene dataframes to create scan test set and miRNA negative test set
scan_test_df = pd.concat([positive_samples_df, scan_neg_df])
mirna_neg_test_df = pd.concat( [positive_samples_df, mirna_neg_set])

print('positive df samples are:', positive_samples_df.shape)
print('scan negative df samples are:', scan_neg_df.shape)
print('scan test df samples are:', scan_test_df.shape)
print('miRNA neg samples are:', mirna_neg_set.shape)
print('mirna neg test df samples are:', mirna_neg_test_df.shape)positive df samples are: (21385, 3)
scan negative df samples are: (427700, 3)
scan test df samples are: (449085, 3)
miRNA neg samples are: (427700, 3)
mirna neg test df samples are: (449085, 3)

## Write output dataset_____no_output_____

scan_test_df.to_csv('scan_test_set.tsv', header=True, index=False, sep='\t')
mirna_neg_test_df.to_csv('mirna_neg_test_set.tsv', header=True, index=False, sep='\t')
encori_train_positive_samples.to_csv(
    'train_set_positives.tsv', header=True, index=False, sep='\t')_____no_output_____! tar -czvf encori_datasets.tar.gz scan_test_set.tsv mirna_neg_test_set.tsv train_set_positives.tsvscan_test_set.tsv
mirna_neg_set.tsv
train_set_positives.tsv


# Notebook from xang1234/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers
Path: Chapter4_TheGreatestTheoremNeverTold/Ch4_LawOfLargeNumbers_PyMC2.ipynb

# Chapter 4
______

## The greatest theorem never told

This chapter focuses on an idea that is always bouncing around our minds, but is rarely made explicit outside books devoted to statistics. In fact, we've been using this simple idea in every example thus far. _____no_output_____### The Law of Large Numbers

Let $Z_i$ be $N$ independent samples from some probability distribution. According to *the Law of Large numbers*,  so long as the expected value $E[Z]$ is finite, the following holds,

$$\frac{1}{N} \sum_{i=1}^N Z_i \rightarrow E[ Z ],  \;\;\; N \rightarrow \infty.$$

In words:

>   The average of a sequence of random variables from the same distribution converges to the expected value of that distribution.

This may seem like a boring result, but it will be the most useful tool you use._____no_output_____### Intuition

If the above Law is somewhat surprising,  it can be made clearer by examining a simple example.

Consider a random variable $Z$ that can take only two values, $c_1$ and $c_2$. Suppose we have a large number of samples of $Z$, denoting a specific sample $Z_i$. The Law says that we can approximate the expected value of $Z$ by averaging over all samples. Consider the average:

$$ \frac{1}{N} \sum_{i=1}^N \;Z_i $$

By construction, $Z_i$ can only take on $c_1$ or $c_2$, hence we can partition the sum over these two values:

\begin{align}
\frac{1}{N} \sum_{i=1}^N \;Z_i
& =\frac{1}{N} \big(  \sum_{ Z_i = c_1}c_1 + \sum_{Z_i=c_2}c_2 \big) \\\\[5pt]
& = c_1 \sum_{ Z_i = c_1}\frac{1}{N} + c_2 \sum_{ Z_i = c_2}\frac{1}{N} \\\\[5pt]
& = c_1 \times \text{ (approximate frequency of $c_1$) } \\\\
& \;\;\;\;\;\;\;\;\; + c_2 \times \text{ (approximate frequency of $c_2$) } \\\\[5pt]
& \approx c_1 \times P(Z = c_1) + c_2 \times P(Z = c_2 ) \\\\[5pt]
& = E[Z]
\end{align}

Equality holds in the limit, but we can get closer and closer by using more and more samples in the average. This Law holds for almost *any distribution*, minus some important cases we will encounter later.

##### Example
____

Below is a diagram of the Law of Large numbers in action for three different sequences of Poisson random variables.

 We sample `sample_size = 100000` Poisson random variables with parameter $\lambda = 4.5$. (Recall the expected value of a Poisson random variable is equal to its parameter.) We calculate the average for the first $n$ samples, for $n=1$ to `sample_size`. _____no_output_____

%matplotlib inline
import numpy as np
from IPython.core.pylabtools import figsize
import matplotlib.pyplot as plt

figsize(12.5, 5)
import pymc as pm

sample_size = 100000
expected_value = lambda_ = 4.5
poi = pm.rpoisson
N_samples = range(1, sample_size, 100)

for k in range(3):

    samples = poi(lambda_, size=sample_size)

    partial_average = [samples[:i].mean() for i in N_samples]

    plt.plot(N_samples, partial_average, lw=1.5, label="average \
of  $n$ samples; seq. %d" % k)

plt.plot(N_samples, expected_value * np.ones_like(partial_average),
         ls="--", label="true expected value", c="k")

plt.ylim(4.35, 4.65)
plt.title("Convergence of the average of \n random variables to its \
expected value")
plt.ylabel("average of $n$ samples")
plt.xlabel("# of samples, $n$")
plt.legend();_____no_output_____

Looking at the above plot, it is clear that when the sample size is small, there is greater variation in the average (compare how *jagged and jumpy* the average is initially, then *smooths* out). All three paths *approach* the value 4.5, but just flirt with it as $N$ gets large. Mathematicians and statistician have another name for *flirting*: convergence.

Another very relevant question we can ask is *how quickly am I converging to the expected value?* Let's plot something new. For a specific $N$, let's do the above trials thousands of times and compute how far away we are from the true expected value, on average. But wait — *compute on average*? This is simply the law of large numbers again! For example, we are interested in, for a specific $N$, the quantity:

$$D(N) = \sqrt{ \;E\left[\;\; \left( \frac{1}{N}\sum_{i=1}^NZ_i  - 4.5 \;\right)^2 \;\;\right] \;\;}$$

The above formulae is interpretable as a distance away from the true value (on average), for some $N$. (We take the square root so the dimensions of the above quantity and our random variables are the same). As the above is an expected value, it can be approximated using the law of large numbers: instead of averaging $Z_i$, we calculate the following multiple times and average them:

$$ Y_k = \left( \;\frac{1}{N}\sum_{i=1}^NZ_i  - 4.5 \; \right)^2 $$

By computing the above many, $N_y$, times (remember, it is random), and averaging them:

$$ \frac{1}{N_Y} \sum_{k=1}^{N_Y} Y_k \rightarrow E[ Y_k ] = E\;\left[\;\; \left( \frac{1}{N}\sum_{i=1}^NZ_i  - 4.5 \;\right)^2 \right]$$

Finally, taking the square root:

$$ \sqrt{\frac{1}{N_Y} \sum_{k=1}^{N_Y} Y_k} \approx D(N) $$ _____no_output_____

figsize(12.5, 4)

N_Y = 250  # use this many to approximate D(N)
N_array = np.arange(1000, 50000, 2500)  # use this many samples in the approx. to the variance.
D_N_results = np.zeros(len(N_array))

lambda_ = 4.5
expected_value = lambda_  # for X ~ Poi(lambda) , E[ X ] = lambda

def D_N(n):
    """
    This function approx. D_n, the average variance of using n samples.
    """
    Z = poi(lambda_, size=(n, N_Y))
    average_Z = Z.mean(axis=0)
    return np.sqrt(((average_Z - expected_value) ** 2).mean())

for i, n in enumerate(N_array):
    D_N_results[i] = D_N(n)

plt.xlabel("$N$")
plt.ylabel("expected squared-distance from true value")
plt.plot(N_array, D_N_results, lw=3,
         label="expected distance between\n\
expected value and \naverage of $N$ random variables.")
plt.plot(N_array, np.sqrt(expected_value) / np.sqrt(N_array), lw=2, ls="--",
         label=r"$\frac{\sqrt{\lambda}}{\sqrt{N}}$")
plt.legend()
plt.title("How 'fast' is the sample average converging? ");_____no_output_____

As expected, the expected distance between our sample average and the actual expected value shrinks as $N$ grows large. But also notice that the *rate* of convergence decreases, that is, we need only 10 000 additional samples to move from 0.020 to 0.015, a difference of 0.005, but *20 000* more samples to again decrease from 0.015  to 0.010, again only a 0.005 decrease.

It turns out we can measure this rate of convergence. Above I have plotted a second line, the function $\sqrt{\lambda}/\sqrt{N}$. This was not chosen arbitrarily. In most cases, given a sequence of random variable distributed like $Z$, the rate of converge to $E[Z]$ of the Law of Large Numbers is

$$ \frac{ \sqrt{ \; Var(Z) \; } }{\sqrt{N} }$$

This is useful to know: for a given large $N$, we know (on average) how far away we are from the estimate. On the other hand, in a Bayesian setting, this can seem like a useless result: Bayesian analysis is OK with uncertainty so what's the *statistical* point of adding extra precise digits? Though drawing samples can be so computationally cheap that having a *larger* $N$ is fine too.

### How do we compute $Var(Z)$ though?

The variance is simply another expected value that can be approximated! Consider the following, once we have the expected value (by using the Law of Large Numbers to estimate it, denote it $\mu$), we can estimate the variance:

$$ \frac{1}{N}\sum_{i=1}^N \;(Z_i - \mu)^2 \rightarrow E[ \;( Z - \mu)^2 \;] = Var( Z )$$

### Expected values and probabilities
There is an even less explicit relationship between expected value and estimating probabilities. Define the *indicator function*

$$\mathbb{1}_A(x) =
\begin{cases} 1 &  x \in A \\\\
              0 &  else
\end{cases}
$$
Then, by the law of large numbers, if we have many samples $X_i$, we can estimate the probability of an event $A$, denoted $P(A)$, by:

$$ \frac{1}{N} \sum_{i=1}^N \mathbb{1}_A(X_i) \rightarrow E[\mathbb{1}_A(X)] =  P(A) $$

Again, this is fairly obvious after a moments thought: the indicator function is only 1 if the event occurs, so we are summing only the times the event occurs and dividing by the total number of trials  (consider how we usually approximate probabilities using frequencies). For example, suppose we wish to estimate the probability that a $Z \sim Exp(.5)$ is greater than 10, and we have many samples from a $Exp(.5)$ distribution.

$$ P( Z > 10 ) = \frac{1}{N} \sum_{i=1}^N \mathbb{1}_{z > 10 }(Z_i) $$
_____no_output_____

import pymc as pm
N = 10000
print(np.mean([pm.rexponential(0.5) > 10 for i in range(N)]))0.0061

### What does this all have to do with Bayesian statistics?

*Point estimates*, to be introduced in the next chapter, in Bayesian inference are computed using expected values. In more analytical Bayesian inference, we would have been required to evaluate complicated expected values represented as multi-dimensional integrals. No longer. If we can sample from the posterior distribution directly, we simply need to evaluate averages. Much easier. If accuracy is a priority, plots like the ones above show how fast you are converging. And if further accuracy is  desired, just take more samples from the posterior.

When is enough enough? When can you stop drawing samples from the posterior? That is the practitioners decision, and also dependent on the variance of the samples (recall from above a high variance means the average will converge slower).

We also should understand when the Law of Large Numbers fails. As the name implies, and comparing the graphs above for small $N$, the Law is only true for large sample sizes. Without this, the asymptotic result is not reliable. Knowing in what situations the Law fails can give us *confidence in how unconfident we should be*. The next section deals with this issue._____no_output_____## The Disorder of Small Numbers

The Law of Large Numbers is only valid as $N$ gets *infinitely* large: never truly attainable.  While the law is a powerful tool, it is foolhardy to apply it liberally. Our next example illustrates this.

##### Example: Aggregated geographic data

Often data comes in aggregated form. For instance, data may be grouped by state, county, or city level. Of course, the population numbers vary per geographic area. If the data is an average of some characteristic of each the geographic areas, we must be conscious of the Law of Large Numbers and how it can *fail* for areas with small populations.

We will observe this on a toy dataset. Suppose there are five thousand counties in our dataset. Furthermore,  population number in each state are uniformly distributed between 100 and 1500. The way the population numbers are generated is irrelevant to the discussion, so we do not justify this. We are interested in measuring the average height of individuals per county. Unbeknownst to us, height does **not** vary across county, and each individual, regardless of the county he or she is currently living in, has the same distribution of what their height may be:

$$ \text{height} \sim \text{Normal}(150, 15 ) $$

We aggregate the individuals at the county level, so we only have data for the *average in the county*. What might our dataset look like?_____no_output_____

figsize(12.5, 4)
std_height = 15
mean_height = 150

n_counties = 5000
pop_generator = pm.rdiscrete_uniform
norm = pm.rnormal

# generate some artificial population numbers
population = pop_generator(100, 1500, size=n_counties)

average_across_county = np.zeros(n_counties)
for i in range(n_counties):
    # generate some individuals and take the mean
    average_across_county[i] = norm(mean_height, 1. / std_height ** 2,
                                    size=population[i]).mean()

# located the counties with the apparently most extreme average heights.
i_min = np.argmin(average_across_county)
i_max = np.argmax(average_across_county)

# plot population size vs. recorded average
plt.scatter(population, average_across_county, alpha=0.5, c="#7A68A6")
plt.scatter([population[i_min], population[i_max]],
            [average_across_county[i_min], average_across_county[i_max]],
            s=60, marker="o", facecolors="none",
            edgecolors="#A60628", linewidths=1.5,
            label="extreme heights")

plt.xlim(100, 1500)
plt.title("Average height vs. County Population")
plt.xlabel("County Population")
plt.ylabel("Average height in county")
plt.plot([100, 1500], [150, 150], color="k", label="true expected \
height", ls="--")
plt.legend(scatterpoints=1);_____no_output_____

What do we observe? *Without accounting for population sizes* we run the risk of making an enormous inference error: if we ignored population size, we would say that the county with the shortest and tallest individuals have been correctly circled. But this inference is wrong for the following reason. These two counties do *not* necessarily have the most extreme heights. The error results from the calculated average of smaller populations not being a good reflection of the true expected value of the population (which in truth should be $\mu =150$). The sample size/population size/$N$, whatever you wish to call it,  is simply too small to invoke the Law of Large Numbers effectively.

We provide more damning evidence against this inference. Recall the population numbers were uniformly distributed over 100 to 1500. Our intuition should tell us that the counties with the most extreme population heights should also be uniformly spread over 100 to 1500, and certainly independent of the county's population. Not so. Below are the population sizes of the counties with the most extreme heights._____no_output_____

print("Population sizes of 10 'shortest' counties: ")
print(population[np.argsort(average_across_county)[:10]])
print("\nPopulation sizes of 10 'tallest' counties: ")
print(population[np.argsort(-average_across_county)[:10]])Population sizes of 10 'shortest' counties:
[100 103 138 182 194 100 118 161 156 186]

Population sizes of 10 'tallest' counties:
[100 147 132 193 270 130 414 101 150 109]

Not at all uniform over 100 to 1500. This is an absolute failure of the Law of Large Numbers.

##### Example:  Kaggle's *U.S. Census Return Rate Challenge*

Below is data from the 2010 US census, which partitions populations beyond counties to the level of block groups (which are aggregates of city blocks or equivalents). The dataset is from a Kaggle machine learning competition some colleagues and I participated in. The objective was to predict the census letter mail-back rate of a group block, measured between 0 and 100, using census variables (median income, number of females in the block-group, number of trailer parks, average number of children etc.). Below we plot the census mail-back rate versus block group population:_____no_output_____

figsize(12.5, 6.5)
data = np.genfromtxt("./data/census_data.csv", skip_header=1,
                     delimiter=",")
plt.scatter(data[:, 1], data[:, 0], alpha=0.5, c="#7A68A6")
plt.title("Census mail-back rate vs Population")
plt.ylabel("Mail-back rate")
plt.xlabel("population of block-group")
plt.xlim(-100, 15e3)
plt.ylim(-5, 105)

i_min = np.argmin(data[:, 0])
i_max = np.argmax(data[:, 0])

plt.scatter([data[i_min, 1], data[i_max, 1]],
            [data[i_min, 0], data[i_max, 0]],
            s=60, marker="o", facecolors="none",
            edgecolors="#A60628", linewidths=1.5,
            label="most extreme points")

plt.legend(scatterpoints=1);_____no_output_____

The above is a classic phenomenon in statistics. I say *classic* referring to the "shape" of the scatter plot above. It follows a classic triangular form, that tightens as we increase the sample size (as the Law of Large Numbers becomes more exact).

I am perhaps overstressing the point and maybe I should have titled the book *"You don't have big data problems!"*, but here again is an example of the trouble with *small datasets*, not big ones. Simply, small datasets cannot be processed using the Law of Large Numbers. Compare with applying the Law without hassle to big datasets (ex. big data). I mentioned earlier that paradoxically big data prediction problems are solved by relatively simple algorithms. The paradox is partially resolved by understanding that the Law of Large Numbers creates solutions that are *stable*, i.e. adding or subtracting a few data points will not affect the solution much. On the other hand, adding or removing data points to a small dataset can create very different results.

For further reading on the hidden dangers of the Law of Large Numbers, I would highly recommend the excellent manuscript [The Most Dangerous Equation](http://nsm.uh.edu/~dgraur/niv/TheMostDangerousEquation.pdf). _____no_output_____##### Example: How to order Reddit submissions

You may have disagreed with the original statement that the Law of Large numbers is known to everyone, but only implicitly in our subconscious decision making. Consider ratings on online products: how often do you trust an average 5-star rating if there is only 1 reviewer? 2 reviewers? 3 reviewers? We implicitly understand that with such few reviewers that the average rating is **not** a good reflection of the true value of the product.

This has created flaws in how we sort items, and more generally, how we compare items. Many people have realized that sorting online search results by their rating, whether the objects be books, videos, or online comments, return poor results. Often the seemingly top videos or comments have perfect ratings only from a few enthusiastic fans, and truly more quality videos or comments are hidden in later pages with *falsely-substandard* ratings of around 4.8. How can we correct this?

Consider the popular site Reddit (I purposefully did not link to the website as you would never come back). The site hosts links to stories or images, and a very popular part of the site are the comments associated with each link. Redditors can vote up or down on each submission (called upvotes and downvotes). Reddit, by default, will sort submissions to a given subreddit by Hot, that is, the submissions that have the most upvotes recently.

How would you determine which submissions are the best? There are a number of ways to achieve this:

1. *Popularity*: A submission is considered good if it has many upvotes. A problem with this model is that a submission with hundreds of upvotes, but thousands of downvotes. While being very popular, the submission is likely more controversial than best.
2. *Difference*: Using the *difference* of upvotes and downvotes. This solves the above problem, but fails when we consider the temporal nature of submission. Depending on when a submission is posted, the website may be experiencing high or low traffic. The difference method will bias the Top submissions to be the those made during high traffic periods, which have accumulated more upvotes than submissions that were not so graced, but are not necessarily the best.
3. *Time adjusted*: Consider using Difference divided by the age of the submission. This creates a *rate*, something like *difference per second*, or *per minute*. An immediate counter-example is, if we use per second, a 1 second old submission with 1 upvote would be better than a 100 second old submission with 99 upvotes. One can avoid this by only considering at least t second old submission. But what is a good t value? Does this mean no submission younger than t is good? We end up comparing unstable quantities with stable quantities (young vs. old submissions).
3. *Ratio*: Rank submissions by the ratio of upvotes to total number of votes (upvotes plus downvotes). This solves the temporal issue, such that new submissions who score well can be considered Top just as likely as older submissions, provided they have many upvotes to total votes. The problem here is that a submission with a single upvote (ratio = 1.0) will beat a submission with 999 upvotes and 1 downvote (ratio = 0.999), but clearly the latter submission is *more likely* to be better.

I used the phrase *more likely* for good reason. It is possible that the former submission, with a single upvote, is in fact a better submission than the latter with 999 upvotes. The hesitation to agree with this is because we have not seen the other 999 potential votes the former submission might get. Perhaps it will achieve an additional 999 upvotes and 0 downvotes and be considered better than the latter, though not likely.

What we really want is an estimate of the *true upvote ratio*. Note that the true upvote ratio is not the same as the observed upvote ratio: the true upvote ratio is hidden, and we only observe upvotes vs. downvotes (one can think of the true upvote ratio as "what is the underlying probability someone gives this submission a upvote, versus a downvote"). So the 999 upvote/1 downvote submission probably has a true upvote ratio close to 1, which we can assert with confidence thanks to the Law of Large Numbers, but on the other hand we are much less certain about the true upvote ratio of the submission with only a single upvote. Sounds like a Bayesian problem to me.

_____no_output_____One way to determine a prior on the upvote ratio is to look at the historical distribution of upvote ratios. This can be accomplished by scraping Reddit's submissions and determining a distribution. There are a few problems with this technique though:

1. Skewed data:  The vast majority of submissions have very few votes, hence there will be many submissions with ratios near the extremes (see the "triangular plot" in the above Kaggle dataset), effectively skewing our distribution to the extremes. One could try to only use submissions with votes greater than some threshold. Again, problems are encountered. There is a tradeoff between number of submissions available to use and a higher threshold with associated ratio precision.
2. Biased data: Reddit is composed of different subpages, called subreddits. Two examples are *r/aww*, which posts pics of cute animals, and *r/politics*. It is very likely that the user behaviour towards submissions of these two subreddits are very different: visitors are likely to be more friendly and affectionate in the former, and would therefore upvote submissions more, compared to the latter, where submissions are likely to be controversial and disagreed upon. Therefore not all submissions are the same.

In light of these, I think it is better to use a `Uniform` prior.

With our prior in place, we can find the posterior of the true upvote ratio. The Python script `top_showerthoughts_submissions.py` will scrape the best posts from the `showerthoughts` community on Reddit. This is a text-only community so the title of each post *is* the post. Below is the top post as well as some other sample posts:_____no_output_____

# adding a number to the end of the %run call will get the ith top post.
%run top_showerthoughts_submissions.py 2

print("Post contents: \n")
print(top_post)Post contents:

Toilet paper should be free and have advertising printed on it.
"""
contents: an array of the text from the last 100 top submissions to a subreddit
votes: a 2d numpy array of upvotes, downvotes for each submission.
"""
n_submissions = len(votes)
submissions = np.random.randint( n_submissions, size=4)
print("Some Submissions (out of %d total) \n-----------"%n_submissions)
for i in submissions:
    print('"' + contents[i] + '"')
    print("upvotes/downvotes: ",votes[i,:], "\n")Some Submissions (out of 98 total)
-----------
"You will never feel how long time is until you have allergies and snot slowly dripping out of your nostrils, while sitting in a classroom with no tissues."
upvotes/downvotes:  [71  6]

"What if porn ads weren't fake and all these years I've been missing out on these local mums in my area that want to fuck?"
upvotes/downvotes:  [43 11]

"You'll be real lucky to find a Penny in Canada."
upvotes/downvotes:  [28 11]

""Smells Like Teen Spirit" is as old to listeners of today as "Yellow Submarine" was to listeners of 1991."
upvotes/downvotes:  [92 10]

 For a given true upvote ratio $p$ and $N$ votes, the number of upvotes will look like a Binomial random variable with parameters $p$ and $N$. (This is because of the equivalence between upvote ratio and probability of upvoting versus downvoting, out of $N$ possible votes/trials). We create a function that performs Bayesian inference on $p$, for a particular comment's upvote/downvote pair._____no_output_____

import pymc as pm

def posterior_upvote_ratio(upvotes, downvotes, samples=20000):
    """
    This function accepts the number of upvotes and downvotes a particular submission received,
    and the number of posterior samples to return to the user. Assumes a uniform prior.
    """
    N = upvotes + downvotes
    upvote_ratio = pm.Uniform("upvote_ratio", 0, 1)
    observations = pm.Binomial("obs", N, upvote_ratio, value=upvotes, observed=True)
    # do the fitting; first do a MAP as it is cheap and useful.
    map_ = pm.MAP([upvote_ratio, observations]).fit()
    mcmc = pm.MCMC([upvote_ratio, observations])
    mcmc.sample(samples, samples / 4)
    return mcmc.trace("upvote_ratio")[:]_____no_output_____

Below are the resulting posterior distributions._____no_output_____

figsize(11., 8)
posteriors = []
colours = ["#348ABD", "#A60628", "#7A68A6", "#467821", "#CF4457"]
for i in range(len(submissions)):
    j = submissions[i]
    posteriors.append(posterior_upvote_ratio(votes[j, 0], votes[j, 1]))
    plt.hist(posteriors[i], bins=18, normed=True, alpha=.9,
             histtype="step", color=colours[i % 5], lw=3,
             label='(%d up:%d down)\n%s...' % (votes[j, 0], votes[j, 1], contents[j][:50]))
    plt.hist(posteriors[i], bins=18, normed=True, alpha=.2,
             histtype="stepfilled", color=colours[i], lw=3, )

plt.legend(loc="upper left")
plt.xlim(0, 1)
plt.title("Posterior distributions of upvote ratios on different submissions");_____no_output_____

Some distributions are very tight, others have very long tails (relatively speaking), expressing our uncertainty with what the true upvote ratio might be.

### Sorting!

We have been ignoring the goal of this exercise: how do we sort the submissions from *best to worst*? Of course, we cannot sort distributions, we must sort scalar numbers. There are many ways to distill a distribution down to a scalar: expressing the distribution through its expected value, or mean, is one way. Choosing the mean is a bad choice though. This is because the mean does not take into account the uncertainty of distributions.

I  suggest using the *95% least plausible value*, defined as the value such that there is only a 5% chance the true parameter is lower (think of the lower bound on the 95% credible region). Below are the posterior distributions with the 95% least-plausible value plotted:_____no_output_____

N = posteriors[0].shape[0]
lower_limits = []

for i in range(len(submissions)):
    j = submissions[i]
    plt.hist(posteriors[i], bins=20, normed=True, alpha=.9,
             histtype="step", color=colours[i], lw=3,
             label='(%d up:%d down)\n%s...' % (votes[j, 0], votes[j, 1], contents[j][:50]))
    plt.hist(posteriors[i], bins=20, normed=True, alpha=.2,
             histtype="stepfilled", color=colours[i], lw=3, )
    v = np.sort(posteriors[i])[int(0.05 * N)]
    # plt.vlines( v, 0, 15 , color = "k", alpha = 1, linewidths=3 )
    plt.vlines(v, 0, 10, color=colours[i], linestyles="--", linewidths=3)
    lower_limits.append(v)
    plt.legend(loc="upper left")

plt.legend(loc="upper left")
plt.title("Posterior distributions of upvote ratios on different submissions");
order = np.argsort(-np.array(lower_limits))
print(order, lower_limits)[0 1 3 2] [0.95553912986585299, 0.94130501756135543, 0.80681345969724116, 0.88775207639838272]

The best submissions, according to our procedure, are the submissions that are *most-likely* to score a high percentage of upvotes. Visually those are the submissions with the 95% least plausible value close to 1.

Why is sorting based on this quantity a good idea? By ordering by the 95% least plausible value, we are being the most conservative with what we think is best.  When using the lower-bound of the 95% credible interval, we believe with high certainty that the 'true upvote ratio' is at the very least equal to this value (or greater), thereby ensuring that the best submissions are still on top. Under this ordering, we impose the following very natural properties:

1. given two submissions with the same observed upvote ratio, we will assign the submission with more votes as better (since we are more confident it has a higher ratio).
2. given two submissions with the same number of votes, we still assign the submission with more upvotes as *better*.

### But this is too slow for real-time!

I agree, computing the posterior of every submission takes a long time, and by the time you have computed it, likely the data has changed. I delay the mathematics to the appendix, but I suggest using the following formula to compute the lower bound very fast.

$$ \frac{a}{a + b} - 1.65\sqrt{ \frac{ab}{ (a+b)^2(a + b +1 ) } }$$

where
\begin{align}
& a = 1 + u \\\\
& b = 1 + d \\\\
\end{align}

$u$ is the number of upvotes, and $d$ is the number of downvotes. The formula is a shortcut in Bayesian inference, which will be further explained in Chapter 6 when we discuss priors in more detail.
_____no_output_____

def intervals(u, d):
    a = 1. + u
    b = 1. + d
    mu = a / (a + b)
    std_err = 1.65 * np.sqrt((a * b) / ((a + b) ** 2 * (a + b + 1.)))
    return (mu, std_err)

print("Approximate lower bounds:")
posterior_mean, std_err = intervals(votes[:, 0], votes[:, 1])
lb = posterior_mean - std_err
print(lb)
print("\n")
print("Top 40 Sorted according to approximate lower bounds:")
print("\n")
order = np.argsort(-lb)
ordered_contents = []
for i in order[:40]:
    ordered_contents.append(contents[i])
    print(votes[i, 0], votes[i, 1], contents[i])
    print("-------------")Approximate lower bounds:
[ 0.9335036   0.95310536  0.94166971  0.90854227  0.88683909  0.85564276
  0.85607414  0.93758888  0.95697574  0.91015237  0.9112593   0.91305389
  0.91341024  0.83335231  0.87543995  0.87081169  0.92748782  0.90747915
  0.89063214  0.89804044  0.91295322  0.78329196  0.91901344  0.79950031
  0.84776174  0.83540757  0.77406294  0.81391583  0.7296015   0.79338766
  0.82895671  0.85331368  0.81849519  0.72362912  0.83662174  0.81019924
  0.78564811  0.84570434  0.8400282   0.76944053  0.85827725  0.74417233
  0.8189683   0.8027221   0.79190256  0.9033107   0.81639188  0.76627386
  0.8010596   0.63657302  0.62988646  0.75041771  0.85355829  0.84522753
  0.75627191  0.8458571   0.80877728  0.66764706  0.69623887  0.71480224
  0.72921035  0.86797314  0.73955911  0.90742546  0.80364062  0.72331349
  0.79249393  0.72708753  0.81109538  0.66235556  0.80480879  0.72039455
  0.73945971  0.83846154  0.69        0.70597731  0.68175931  0.59412132
  0.6011942   0.73158407  0.69121436  0.68134548  0.87746603  0.79809005
  0.6296728   0.87152685  0.81814153  0.86498277  0.81018384  0.54207776
  0.6296728   0.74107856  0.53025484  0.71034959  0.80149882  0.85773646
  0.58343356  0.62971097]

Top 40 Sorted according to approximate lower bounds:

586 18 Someone should develop an AI specifically for reading Terms & Conditions and flagging dubious parts.
-------------
2354 98 Porn is the only industry where it is not only acceptable but standard to separate people based on race, sex and sexual preference.
-------------
1924 101 All polls are biased towards people who are willing to take polls
-------------
949 50 They should charge less for drinks in the drive-thru because you can't refill them.
-------------
3726 238 When I was in elementary school and going through the DARE program, I was positive a gang of older kids was going to corner me and force me to smoke pot. Then I became an adult and realized nobody is giving free drugs to somebody that doesn't want them.
-------------
164 7 "Noted" is the professional way of saying "K".
-------------
100 4 The best answer to the interview question "What is your greatest weakness?" is "interviews".
-------------
267 17 At some point every parent has stopped wiping their child's butt and hoped for the best.
-------------
291 19 You've been doing weird cameos in your friends' dreams since kindergarten.
-------------
121 6 Is it really fair to say a person over 85 has heart failure? Technically, that heart has done exceptionally well.
-------------
523 39 I wonder if America's internet is censored in a similar way that North Korea's is, but we have no idea of it happening.
-------------
539 41 It's surreal to think that the sun and moon and stars we gaze up at are the same objects that have been observed for millenia, by everyone in the history of humanity from cavemen to Aristotle to Jesus to George Washington.
-------------
1509 131 Kenny's family is poor because they're always paying for his funeral.
-------------
164 10 Black hair ties are probably the most popular bracelets in the world.
-------------
26 0 Now that I am a parent of multiple children I have realized that my parents were lying through their teeth when they said they didn't have a favorite.
-------------
41 1 If I was as careful with my whole paycheck as I am with my last $20 I'd be a whole lot better off
-------------
125 8 Surfing the internet without ads feels like a summer evening without mosquitoes
-------------
157 12 I wonder if Superman ever put a pair of glasses on Lois Lane's dog, and she was like "what's this Clark? Did you get me a new dog?"
-------------
1411 157 My life is really like Rihanna's song, "just work work work work work" and the rest of it I can't really understand.
-------------
19 0 Binoculars are like walkie talkies for the deaf.
-------------
221 22 I'm honestly slightly concerned how often Reddit commenters make me laugh compared to my real life friends.
-------------
18 0 Living on the coast is having the window seat of the land you live on.
-------------
188 19 I have not been thankful enough in the last few years that the Black Eyed Peas are no longer ever on the radio
-------------
29 1 Rewatching Mr. Bean, I've realised that the character is an eccentric genius and not a blithering idiot.
-------------
17 0 Sitting on a cold toilet seat or a warm toilet seat both suck for different reasons.
-------------
54 4 You will never feel how long time is until you have allergies and snot slowly dripping out of your nostrils, while sitting in a classroom with no tissues.
-------------
16 0 I sneer at people who read tabloids, but every time I look someone up on Wikipedia the first thing I look for is what controversies they've been involved in.
-------------
1485 222 Kid's menus at restaurants should be smaller portions of the same adult dishes at lower prices and not the junk food that they usually offer.
-------------
1417 212 Eventually once all phones are waterproof we'll be able to push people into pools again
-------------
35 2 Childhood and adolescence are thinking that no one has ever felt the way you do and that no one has ever experienced the things that you have. Adulthood is realizing that almost everyone has felt and experienced something similar.
-------------
60 5 Myspace is so outdated that jokes about it being outdated has become outdated
-------------
87 9 Yahoo!® is the RadioShack® of the Internet.
-------------
33 2 People who "tell it like it is" rarely do so to say something nice
-------------
49 4 The world must have been a spookier place altogether when candles and gas lamps were the only sources of light at night besides the moon and the stars.
-------------
41 3 Closing your eyes after turning off your alarm is a very dangerous game.
-------------
47 4 As a kid, seeing someone step on a banana peel and not slip was a disappointment.
-------------
23 1 The phonebook was the biggest invasion of privacy that everyone was oddly ok with.
-------------
53 5 I'm actually the most productive when I procrastinate because I'm doing everything I possibly can to avoid the main task at hand.
-------------
86 10 "Smells Like Teen Spirit" is as old to listeners of today as "Yellow Submarine" was to listeners of 1991.
-------------
240 36 if an ocean didnt stop immigrants from coming to America what makes us think a wall will?
-------------

We can view the ordering visually by plotting the posterior mean and bounds, and sorting by the lower bound. In the plot below, notice that the left error-bar is sorted (as we suggested this is the best way to determine an ordering), so the means, indicated by dots, do not follow any strong pattern. _____no_output_____

r_order = order[::-1][-40:]
plt.errorbar(posterior_mean[r_order], np.arange(len(r_order)),
             xerr=std_err[r_order], capsize=0, fmt="o",
             color="#7A68A6")
plt.xlim(0.3, 1)
plt.yticks(np.arange(len(r_order) - 1, -1, -1), map(lambda x: x[:30].replace("\n", ""), ordered_contents));_____no_output_____

In the graphic above, you can see why sorting by mean would be sub-optimal._____no_output_____### Extension to Starred rating systems

The above procedure works well for upvote-downvotes schemes, but what about systems that use star ratings, e.g. 5 star rating systems. Similar problems apply with simply taking the average: an item with two perfect ratings would beat an item with thousands of perfect ratings, but a single sub-perfect rating.

We can consider the upvote-downvote problem above as binary: 0 is a downvote, 1 if an upvote. A $N$-star rating system can be seen as a more continuous version of above, and we can set $n$ stars rewarded is equivalent to rewarding $\frac{n}{N}$. For example, in a 5-star system, a 2 star rating corresponds to 0.4. A perfect rating is a 1. We can use the same formula as before, but with $a,b$ defined differently:

$$ \frac{a}{a + b} - 1.65\sqrt{ \frac{ab}{ (a+b)^2(a + b +1 ) } }$$

where

\begin{align}
& a = 1 + S \\\\
& b = 1 + N - S \\\\
\end{align}

where $N$ is the number of users who rated, and $S$ is the sum of all the ratings, under the equivalence scheme mentioned above. _____no_output_____##### Example: Counting Github stars

What is the average number of stars a Github repository has? How would you calculate this? There are over 6 million repositories, so there is more than enough data to invoke the Law of Large numbers. Let's start pulling some data. TODO_____no_output_____### Conclusion

While the Law of Large Numbers is cool, it is only true so much as its name implies: with large sample sizes only. We have seen how our inference can be affected by not considering *how the data is shaped*.

1. By (cheaply) drawing many samples from the posterior distributions, we can ensure that the Law of Large Number applies as we approximate expected values (which we will do in the next chapter).

2. Bayesian inference understands that with small sample sizes, we can observe wild randomness. Our posterior distribution will reflect this by being more spread rather than tightly concentrated. Thus, our inference should be correctable.

3. There are major implications of not considering the sample size, and trying to sort objects that are unstable leads to pathological orderings. The method provided above solves this problem.
_____no_output_____### Appendix

##### Derivation of sorting comments formula

Basically what we are doing is using a Beta prior (with parameters $a=1, b=1$, which is a uniform distribution), and using a Binomial likelihood with observations $u, N = u+d$. This means our posterior is a Beta distribution with parameters $a' = 1 + u, b' = 1 + (N - u) = 1+d$. We then need to find the value, $x$, such that 0.05 probability is less than $x$. This is usually done by inverting the CDF ([Cumulative Distribution Function](http://en.wikipedia.org/wiki/Cumulative_Distribution_Function)), but the CDF of the beta, for integer parameters, is known but is a large sum [3].

We instead use a Normal approximation. The mean of the Beta is $\mu = a'/(a'+b')$ and the variance is

$$\sigma^2 = \frac{a'b'}{ (a' + b')^2(a'+b'+1) }$$

Hence we solve the following equation for $x$ and have an approximate lower bound.

$$ 0.05 = \Phi\left( \frac{(x - \mu)}{\sigma}\right) $$

$\Phi$ being the [cumulative distribution for the normal distribution](http://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution)

_____no_output_____##### Exercises

1\. How would you estimate the quantity $E\left[ \cos{X} \right]$, where $X \sim \text{Exp}(4)$? What about $E\left[ \cos{X} | X \lt 1\right]$, i.e. the expected value *given* we know $X$ is less than 1? Would you need more samples than the original samples size to be equally accurate?_____no_output_____

# Enter code here
import scipy.stats as stats
exp = stats.expon(scale=4)
N = int(1e5)
X = exp.rvs(N)
# ...
X.mean()_____no_output_____X[X <1].mean()_____no_output_____len(X[X<1])_____no_output_____N = int(5*1e5)
X = exp.rvs(N)
len(X[X<1])_____no_output_____X[X <1].mean()_____no_output_____

2\. The following table was located in the paper "Going for Three: Predicting the Likelihood of Field Goal Success with Logistic Regression" [2]. The table ranks football field-goal kickers by their percent of non-misses. What mistake have the researchers made?

**Lower number of samples**

-----

####  Kicker Careers Ranked by Make Percentage

Rank 	Kicker 	Make % 	Number  of Kicks

1 	Garrett Hartley 	87.7 	57

2	 Matt Stover 	86.8 	335

3 	Robbie Gould 	86.2 	224

4 	Rob Bironas 	86.1 	223

5	 Shayne Graham 	85.4 	254

… 	… 	…

51	 Dave Rayner 	72.2 	90

52	 Nick Novak 	71.9 	64

53 	Tim Seder 	71.0 	62

54 	Jose Cortez 	70.7	 75

55 	Wade Richey 	66.1	 56

_____no_output_____In August 2013, [a popular post](http://bpodgursky.wordpress.com/2013/08/21/average-income-per-programming-language/) on the average income per programmer of different languages was trending. Here's the summary chart: (reproduced without permission, cause when you lie with stats, you gunna get the hammer). What do you notice about the extremes?

**Lower number of samples**

------

#### Average household income by programming language

Language	Average Household Income ($)	Data Points

Puppet	87,589.29	112

Haskell	89,973.82	191

PHP	94,031.19	978

CoffeeScript	94,890.80	435

VimL	94,967.11	532

Shell	96,930.54	979

Lua	96,930.69	101

Erlang	97,306.55	168

Clojure	97,500.00	269

Python	97,578.87	2314

JavaScript	97,598.75	3443

Emacs Lisp	97,774.65	355

C#	97,823.31	665

Ruby	98,238.74	3242

C++	99,147.93	845

CSS	99,881.40	527

Perl	100,295.45	990

C	100,766.51	2120

Go	101,158.01	231

Scala	101,460.91	243

ColdFusion	101,536.70	109

Objective-C	101,801.60	562

Groovy	102,650.86	116

Java	103,179.39	1402

XSLT	106,199.19	123

ActionScript	108,119.47	113

_____no_output_____### References

1. Wainer, Howard. *The Most Dangerous Equation*. American Scientist, Volume 95.
2. Clarck, Torin K., Aaron W. Johnson, and Alexander J. Stimpson. "Going for Three: Predicting the Likelihood of Field Goal Success with Logistic Regression." (2013): n. page. [Web](http://www.sloansportsconference.com/wp-content/uploads/2013/Going%20for%20Three%20Predicting%20the%20Likelihood%20of%20Field%20Goal%20Success%20with%20Logistic%20Regression.pdf). 20 Feb. 2013.
3. http://en.wikipedia.org/wiki/Beta_function#Incomplete_beta_function_____no_output_____

from IPython.core.display import HTML

def css_styling():
    styles = open("../styles/custom.css", "r").read()
    return HTML(styles)
css_styling()_____no_output_____

_____no_output_____