Skip to content

Instantly share code, notes, and snippets.

@JonathanRaiman
JonathanRaiman / Arrays of Cython Structs
Created December 16, 2014 06:10
Little trivial example of memory allocation and deallocation in cython with arrays, points, structs, and more...
from libc.stdlib cimport malloc, free, realloc
cdef struct Chair:
int size
cdef class Bench:
cdef Chair* chairs
cdef readonly int num_chairs
property chairs:
@JonathanRaiman
JonathanRaiman / Cython & BLAS gemm
Last active August 29, 2015 14:08
Cython & BLAS gemm
# How to get gemm to work in Cython
# 1. suppose your data is Fortran contiguous (really ?)
# then blas supports this out of the box:
%%cython
cimport numpy as np
import numpy as np
from cpython cimport PyCapsule_GetPointer # PyCObject_AsVoidPtr
@JonathanRaiman
JonathanRaiman / Cython Vector Outer Product
Created November 4, 2014 05:44
Take the outer product for all pairs of vectors in two matrices (np.outer(A, B, axis = 1) essentially)
%%cython
import cython
from cython cimport view
import numpy as np
cimport numpy as np
from cpython cimport PyCapsule_GetPointer # PyCObject_AsVoidPtr
from scipy.linalg.blas import fblas
REAL = np.float32
@JonathanRaiman
JonathanRaiman / Cython Outer Product
Created November 4, 2014 03:55
Outer product in Cython
%%cython
import cython
import numpy as np
cimport numpy as np
from libc.math cimport exp
from libc.string cimport memset
from cpython cimport PyCapsule_GetPointer # PyCObject_AsVoidPtr
@JonathanRaiman
JonathanRaiman / Theano Gaussian Kernel
Created November 2, 2014 01:33
A Gaussian Kernel in Theano
import theano, theano.tensor as T, numpy as np
def _outer_substract(x, y):
x = x.dimshuffle(0, 1, 'x')
x = T.addbroadcast(x, 2)
return (x - y.T).T
def _gaussian_kernel(x, y, beta = 0.1):
K = _outer_substract(x,y)
return T.exp( -beta * K.norm(L=2,axis=1))
x = T.matrix()
# coding: utf-8
#
# @author Jonathan Raiman
# @date 9th October 2014
#
# Messing around with Stanford's GloVe words
# Download them [here](http://www-nlp.stanford.edu/projects/glove/)
import gzip, numpy as np, io