Skip to content

Instantly share code, notes, and snippets.

View tansey's full-sized avatar

Wesley Tansey tansey

View GitHub Profile
@tansey
tansey / factor_pav.py
Last active May 11, 2019 18:38
Pool adjacent violators algorithm for monotone matrix factorization
'''Pool adjacent violators algorithm for (column-)monotone matrix factorization.
Applies the PAV algorithm to column factors of a matrix factorization:
Given: M = W.V'
Returns: V_proj, a projected version of V such that M[i] is monotone decreasing
for all i.
Author: Wesley Tansey
Date: May 2019
'''
@tansey
tansey / fitWeightedNegativeBinomial.R
Created July 2, 2017 16:18
Fit negative binomial with weighted observations in R
# Fit using a simple EM algorithm
# observations are x
# weights are w (must be same length as x)
# returns (r, p)
# r - dispersion parameter
# p - probability of success
weightedNegBinomFit <- function(x, w, maxsteps=30)
{
sum.wx = sum(x*w)
sum.w = sum(w)
@tansey
tansey / chol_unpack.py
Created February 10, 2017 21:48
Unpack a lower triangular Cholesky matrix from a neural network output in Tensorflow
import tensorflow as tf
def unpack_cholesky(q, ndims):
# Build the lower-triangular Cholesky from the flat buffer (assumes q shape is [batchsize, cholsize])
chol_diag = tf.nn.softplus(q[:,:ndims])
chol_offdiag = q[:,ndims:]
chol_rows = []
chol_start = 0
chol_end = 1
for i in xrange(ndims):
@tansey
tansey / wtfset.cpp
Created November 9, 2016 02:57
terrible STL set iterator behavior
#include <set>
#include <iostream>
class A
{
std::set<int> s;
public:
A() { s.insert(0); s.insert(1); }
std::set<int> getSet() { return s; }
@tansey
tansey / plot_with_bands.py
Last active January 3, 2016 17:38
Plot means with confidence (stderr or other metric) bands in a pretty format using matplotlib.
def plot_with_bands(graph_title, means, bands, series, xvals=None, xlabel=None, ylabel=None, subtitle=None, filename='results.pdf'):
colors = ['blue','red','green', 'black', 'yellow', 'orange', 'purple', 'brown'] # max 8 lines
print 'means: {0} bands: {1}'.format(means.shape, bands.shape)
assert(means.shape == bands.shape)
assert(xvals is None or xvals.shape[0] == means.shape[1])
assert(means.shape[1] <= len(colors))
if xvals is None:
xvals = np.arange(means.shape[0])
ax = plt.subplot(111)
plt.ticklabel_format(axis='y', style='plain', useOffset=False)
@tansey
tansey / gist:6977878
Created October 14, 2013 15:55
2 parameter gibbs sampler with pretty plots
import random
import math
import matplotlib.pyplot as plt
import numpy as np
def acf(x, length=35):
return np.array([1] + [np.corrcoef(x[:-i], x[i:])[0,1] for i in range(1,length)])
# The number of samples to observe
n = 100
class A(object):
def __init__(self, myvar = {}):
self.myvar = myvar
a1 = A()
a1.myvar['foo'] = 1
a2 = A()
a2.myvar['bar'] = 2
class A(object):
def __init__(self, myvar = {}):
self.myvar = myvar
a1 = A()
a1.myvar['foo'] = 1
a2 = A()
a2.myvar['bar'] = 2
@tansey
tansey / gist:2410545
Created April 18, 2012 02:00
Training a NEAT network with backprop in SharpNEAT
double[] inputs = ...
double[] desiredOutputs = ...
// Get the neural network
var network = ((FastCyclicNetwork)blackbox;
// Perform backpropagation through time
network.Train(inputs, desiredOutputs);
@tansey
tansey / gist:2410490
Created April 18, 2012 01:50
Lamarckian evolution in SharpNEAT
/// <summary>
/// Saves all phenotypic progress back to the genomes.
/// </summary>
private void PerformLamarkianEvolution(IList<TGenome> genomeList, Func<IAgent, FastCyclicNetwork> networkSelector)
{
for (int i = 0; i < _agents.Length; i++)
{
var agent = _agents[i];
// Get the network for this teacher