Skip to content

Instantly share code, notes, and snippets.

@stober
stober / create_rdict.py
Created May 10, 2011 18:10
Reversing a Dictionary
def create_rdict(d):
"""
Return a dictionary with each value mapping to a set of keys.
"""
rd = {}
for (key,value) in d.items():
v = rd.setdefault(value, set([]))
v.add(key)
return rd
@stober
stober / create_rdict_alt.py
Created May 10, 2011 18:13
Reversing a Dictionary (Alternate)
def create_rdict(d):
"""
Return a dictionary with each value mapping to a set of keys.
"""
rd = {}
for (key,value) in d.items():
if rd.has_key(value):
rd[value].add(key)
else:
rd[value] = set([key])
@stober
stober / flat_dict.py
Created May 10, 2011 18:14
Flatten a Dictionary of Sets
def flat_dict(d):
"""
Return a dict where sets are replaced by a single element of each
set. Compose with create_rdict to reverse a 1-1 dict.
"""
nd = {}
for (key, value) in d.items():
nd[key] = value.pop()
return nd
@stober
stober / flip.py
Created May 10, 2011 18:22
Flip a Coin
import random as pr
def flip(p):
""" Flip a biased coin. """
if pr.random() < p:
return True
else:
return False
@stober
stober / egreedy.py
Created May 14, 2011 00:38
Epsilon Greedy N-Armed Bandit Solver
# J. Stober
# May 13, 2011
import numpy as np
import numpy.random as nr
class EGreedy(object):
def __init__(self, k = 10, epsilon = 0.1):
@stober
stober / gmm.py
Created June 15, 2011 17:10
Gaussian Mixture Model
#!/usr/bin/python
"""
Author: Jeremy M. Stober
Program: GMM.PY
Date: Thursday, September 4 2008
Description: Fit a Gaussian Mixture Model with EM.
"""
import os, sys, getopt, pdb, string
from numpy import *
@stober
stober / ipickle.py
Created October 25, 2011 22:02
Problems with Pickle and IPython
class A:
pass
if __name__ == '__main__':
import pickle
pickle.dump(A(), open("A.pck","w"))
a = pickle.load(open("A.pck"))
print a
@stober
stober / normal.py
Created November 9, 2011 21:30
Normal Distribution
#! /usr/bin/env python
"""
Author: Jeremy M. Stober
Program: NORMAL.PY
Date: Friday, July 7, 2011
Description: Manipulating normal distributions.
"""
import numpy as np
import numpy.linalg as la
@stober
stober / pca.py
Created February 10, 2012 19:05
Principle Component Analysis in Python
import numpy as np
# Unlike other implementations, this can handle very high dimensional data (like images).
def compute_pca(data):
m = np.mean(data, axis=0)
datac = np.array([obs - m for obs in data])
T = np.dot(datac, datac.T)
[u,s,v] = np.linalg.svd(T)
@stober
stober / tiles.py
Created February 10, 2012 20:46
Tile Coding in Python
#!/usr/bin/python
"""
Author: Jeremy M. Stober
Program: TILES.PY
Date: Monday, March 31 2008
Description: A simple CMAC implementation.
"""
import os, sys, getopt, pdb
from numpy import *